package cif

import (
	"time"

	"git.fjla.uk/owlboard/timetable-mgr/dbAccess"
	"git.fjla.uk/owlboard/timetable-mgr/helpers"
	"git.fjla.uk/owlboard/timetable-mgr/log"
	"go.uber.org/zap"
)

func CifCheck(cfg *helpers.Configuration) {
	log.Msg.Info("Checking age of CIF Data")
	utime, err := dbAccess.CheckUpdateTime(dbAccess.TimetableCollection)
	if err != nil {
		log.Msg.Error("Error checking last timetable update", zap.Error(err))
	}

	lastUpdate := time.Unix(utime, 0)
	currentTime := time.Now().In(time.UTC)
	london, _ := time.LoadLocation("Europe/London")
	londonTime := currentTime.In(london)
	dataAge := currentTime.Sub(lastUpdate)
	maxAge := 22 * time.Hour

	log.Msg.Debug("CIF Data", zap.Duration("Data Age", dataAge), zap.Duration("Max Age", maxAge))

	if dataAge >= maxAge {
		log.Msg.Warn("Timetable data is more than 24 hours old")
		if londonTime.Hour() >= updateHour {
			runUpdate("daily")
		} else {
			log.Msg.Debug("Timetable update is required but data is not yet available")
		}
	} else if dataAge > 48 {
		log.Msg.Warn("Timetable data is more than 48 hours old")
		if londonTime.Hour() >= updateHour {
			runUpdate("full")
		} else {
			log.Msg.Debug("Waiting until todays data is available before updating")
		}
	} else {
		log.Msg.Info("Timetable data is less than 24 hours old")
	}
}
