package cif

import (
	"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"
)

// Loads CifMetadata and passes it to parseMetadata, this function is what you should call to initiate the CifUpdate process.
func CifCheck(cfg *helpers.Configuration) error {
	log.Msg.Debug("Checking age of CIF Data")
	metadata, err := dbAccess.GetCifMetadata()
	if err != nil {
		return err
	}

	err = parseMetadata(metadata, cfg)
	if err != nil {
		log.Msg.Error("Error updating CIF Data", zap.Error(err))
		return err
	}

	return nil
}

// Requests a full update if no metadata exists, or a daily update if metadata does exist.
// The daily update function does further metadata parsing to determine what exactly needs downloading.
func parseMetadata(metadata *dbAccess.CifMetadata, cfg *helpers.Configuration) error {
	if metadata == nil {
		log.Msg.Info("No metadata, creating Timetable data")
		newMeta, err := runFullUpdate(cfg)
		if err != nil {
			return err
		}
		ok := dbAccess.PutCifMetadata(*newMeta)
		if !ok {
			log.Msg.Error("CIF Data updated but Metadata Update failed")
		}
		return nil
	}

	log.Msg.Debug("Requesting CIF Data Update")
	newMeta, err := runUpdate("daily", metadata)
	if err != nil {
		return err
	}
	ok := dbAccess.PutCifMetadata(*newMeta)
	if !ok {
		log.Msg.Error("CIF Data updated but Metadata Update failed")
	}
	return nil
}
