package database

import (
	"errors"
	"io/fs"
	"os"
	"time"

	"gordenko.dev/dima/qb"
	"gordenko.dev/dima/qb/proto"
)

func timeBoundsOfAggregation(since, until proto.TimeBound, groupBy qb.GroupBy, firstHourOfDay int) (s time.Time, u time.Time) {
	switch groupBy {
	case qb.GroupByHour, qb.GroupByDay:
		s = time.Date(since.Year, since.Month, since.Day, 0, 0, 0, 0, time.Local)
		u = time.Date(until.Year, until.Month, until.Day, 0, 0, 0, 0, time.Local)

	case qb.GroupByMonth:
		s = time.Date(since.Year, since.Month, 1, 0, 0, 0, 0, time.Local)
		u = time.Date(until.Year, until.Month, 1, 0, 0, 0, 0, time.Local)
	}

	if firstHourOfDay > 0 {
		duration := time.Duration(firstHourOfDay) * time.Hour
		s = s.Add(duration)
		u = u.Add(duration)
	}

	u = u.Add(-1 * time.Second)
	return
}

func isFileExist(fileName string) (bool, error) {
	_, err := os.Stat(fileName)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return false, nil
		} else {
			return false, err
		}
	} else {
		return true, nil
	}
}

func correctToFHD(since, until uint32, firstHourOfDay int) (uint32, uint32) {
	duration := time.Duration(firstHourOfDay) * time.Hour
	since = uint32(time.Unix(int64(since), 0).Add(duration).Unix())
	until = uint32(time.Unix(int64(until), 0).Add(duration).Unix())
	return since, until
}
