package main

import (
	// External
	werr "git.ahall.se/go/wrappederror"

	// Standard
	"time"
)

func timefilterParse(timeFromStr, timeToStr, offset, preset string) (timeFrom, timeTo time.Time, err error) {
	if preset != "" {
		presetTimeInterval(time.Hour, preset, &timeFrom, &timeTo)
		return
	}

	yesterday := time.Now().Add(time.Duration(-24 * time.Hour))
	timeFrom, err = parseHTMLDateTime(timeFromStr, yesterday)
	if err != nil {
		err = werr.Wrap(err).WithData(timeFromStr)
		return
	}

	timeTo, err = parseHTMLDateTime(timeToStr, time.Now())
	if err != nil {
		err = werr.Wrap(err).WithData(timeToStr)
		return
	}

	// Protect the user from switching from/to dates, leading to
	// zero matching values from the database.
	if timeFrom.After(timeTo) {
		timeFrom, timeTo = timeTo, timeFrom
	}

	// Apply an optionally set offset (in seconds).
	timeFrom = applyTimeOffset(timeFrom, time.Second, offset)
	timeTo = applyTimeOffset(timeTo, time.Second, offset)

	return
}
