package database

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

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

func timeBoundsOfAggregation(since, until proto.TimeBound, groupBy diploma.GroupBy, firstHourOfDay int) (s time.Time, u time.Time) {
	switch groupBy {
	case diploma.GroupByHour, diploma.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, 23, 59, 59, 0, time.Local)

	case diploma.GroupByMonth:
		s = time.Date(since.Year, since.Month, 1, 0, 0, 0, 0, time.Local)
		u = time.Date(until.Year, until.Month, 1, 23, 59, 59, 0, time.Local)
		u = u.AddDate(0, 1, 0)
		u = u.AddDate(0, 0, -1)
	}

	if firstHourOfDay > 0 {
		duration := time.Duration(firstHourOfDay) * time.Hour
		s = s.Add(duration)
		u = u.Add(duration)
	}
	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 (s *Database) appendJobToWorkerQueue(job any) {
	s.mutex.Lock()
	s.workerQueue = append(s.workerQueue, job)
	s.mutex.Unlock()

	select {
	case s.workerSignalCh <- struct{}{}:
	default:
	}
}

func (s *Database) metricRUnlock(metricID uint32) {
	s.mutex.Lock()
	s.rLocksToRelease = append(s.rLocksToRelease, metricID)
	s.mutex.Unlock()

	select {
	case s.workerSignalCh <- struct{}{}:
	default:
	}
}
