package parser

import (
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"time"
)

const (
	dateFormat = "2006-01-02T15:04:05.999999-0700"
)

func processKeyValue(currentRecord *ParserRecord, currentRecordProcessed *bool, currentRecordErrors *bool, key string, value string) {
	switch key {
	case "timestamp":
		x, err := processTimestamp(value)
		if err != nil {
			currentRecord.Date = emptyTime
			*currentRecordErrors = true
			return
		}
		currentRecord.Date = *x
	case "query":
		x, err := processQuery(value)
		if err != nil {
			currentRecord.URL = ""
			*currentRecordErrors = true
			return
		}
		currentRecord.URL = x
	case "workflow":
		x, err := processWorkflow(value)
		if err != nil {
			currentRecord.Code = -1
			*currentRecordErrors = true
			return
		}
		currentRecord.Code = x
		*currentRecordProcessed = true
	case "ip_port":
	case "work_time":
	case "referer":
	case "host":
	}
}

func processTimestamp(str string) (*time.Time, error) {
	ts, err := time.Parse(dateFormat, str)
	if err != nil {
		return nil, err
	}

	return &ts, err
}

func processQuery(str string) (string, error) {
	rawData := strings.Split(str, " ")
	if len(rawData) != 3 {
		return "", fmt.Errorf("incorrect query string %s", str)
	}

	if len(rawData[0]) == 0 || len(rawData[2]) == 0 {
		return "", fmt.Errorf("incorrect query string %s", str)
	}

	u, err := url.ParseRequestURI(rawData[1])
	if err != nil {
		return "", err
	}

	return u.EscapedPath(), nil
}

func processWorkflow(str string) (int, error) {
	if strings.LastIndex(str, "cache hit") != -1 {
		return 200, nil
	}

	if idx := strings.LastIndex(str, "succ"); idx != -1 {
		code, err := strconv.Atoi(str[idx+5 : idx+8])
		if err != nil {
			return -1, nil
		}

		return code, nil
	}

	return -1, fmt.Errorf("could not find cache hit or proxy request in workflow")
}

func processEndOfRecord(currentRecord *ParserRecord, errSlice *[]ParserRecord, succSlice *[]ParserRecord) {
	if currentRecord.Date.Equal(emptyTime) || currentRecord.URL == emptyString || currentRecord.Code == -1 {
		return
	}

	if currentRecord.URL != "/ok.html" &&
		currentRecord.URL != "/ping" &&
		currentRecord.URL != "/l7ping" &&
		!strings.HasPrefix(currentRecord.URL, "/awacs-balancer-health-check") {

		if currentRecord.Code != 200 && currentRecord.Code != 304 && currentRecord.Code != 206 && currentRecord.Code != 301 && currentRecord.Code != 302 {
			*errSlice = append(*errSlice, *currentRecord)
		} else {
			*succSlice = append(*succSlice, *currentRecord)
		}
	}
}
