package internal

import (
	"fmt"
	"net/http"
	"strconv"
	"time"
)

func (a *adminHandler) getStats(r *http.Request) (*RestResponse, error) {
	q := r.URL.Query()
	startFilter := q.Get("start")
	endFilter := q.Get("end")
	key := q.Get("key")
	intervalSecondsStr := q.Get("interval")

	var err error
	start := time.Now().UTC().Add(time.Hour * -86400)
	end := time.Now().UTC()

	if startFilter != "" {
		if start, err = time.Parse(ISO8601, startFilter); err != nil {
			return BasicResponse(false, fmt.Sprintf("start: could not understand value `%v`", err.Error())), nil
		}
	}

	if endFilter != "" {
		if end, err = time.Parse(ISO8601, endFilter); err != nil {
			return BasicResponse(false, fmt.Sprintf("end: could not understand value `%v`", err.Error())), nil
		}
	}

	lai := LogAggregateInput{
		Start:  start,
		End:    end,
		Column: key,
	}

	if intervalSecondsStr != "" {
		if lai.IntervalSeconds, err = strconv.Atoi(intervalSecondsStr); err != nil {
			return BasicResponse(false, "interval query param must be a valid whole number"), nil
		}
	}

	la, err := a.Storage.GetLogAggregate(lai)
	if err != nil {
		return nil, err
	}

	return BasicResponse(true, la), nil

}

type LogFilter struct {
	Expression string
}

func (a *adminHandler) getLog(r *http.Request) (*RestResponse, error) {
	q := r.URL.Query()
	startFilter := q.Get("start")
	endFilter := q.Get("end")
	// filter := LogFilter{Expression: q.Get("filter")}
	pageStr := q.Get("page")

	var err error
	var page int
	start := time.Now().UTC().Add(time.Hour * -86400)
	end := time.Now().UTC()

	if startFilter != "" {
		if start, err = time.Parse(ISO8601, startFilter); err != nil {
			return BasicResponse(false, "start: not a valid start time"), nil
		}
	}

	if endFilter != "" {
		if end, err = time.Parse(ISO8601, endFilter); err != nil {
			return BasicResponse(false, "end: not a valid end time"), nil
		}
	}

	if pageStr != "" {
		if page, err = strconv.Atoi(pageStr); err != nil {
			return BasicResponse(false, "page: must be a valid integer"), nil

		}
	}

	gli := GetLogInput{
		// Filter: filter,
		Start: start,
		End:   end,
		Limit: 250,
		Page:  page,
	}

	// if err := gli.Validate(); err != nil {
	// 	return BasicResponse(false, err.Error()), nil
	// }

	ql, err := a.Storage.GetLog(gli)
	if err != nil {
		return nil, err
	}

	return BasicResponse(true, ql), nil
}
