package daemons

import (
	"oc-schedulerd/conf"
	"os"
	"time"

	oclib "cloud.o-forge.io/core/oc-lib"
)

var Bookings = ScheduledBooking{Bookings: []Booking{}}

type ExecutionManager struct{}

// Loop every second on the booking's list and move the booking that must start to a new list
// that will be looped over to start them
func (em *ExecutionManager) RetrieveNextExecutions() {
	logger := oclib.GetLogger()
	for {
		logger.Debug().Msg("New loop")
		Bookings.Mu.Lock()
		if len(Bookings.Bookings) > 0 {
			for i := len(Bookings.Bookings) - 1; i >= 0; i-- {
				logger.Debug().Msg("It should start at " + Bookings.Bookings[i].Start.String() + " and it is now " + time.Now().UTC().String())
				if Bookings.Bookings[i].Start.Before(time.Now().UTC()) {
					logger.Info().Msg("Will execute " + Bookings.Bookings[i].Workflow + " soon")
					go em.executeBooking(Bookings.Bookings[i])
					Bookings.Bookings = append(Bookings.Bookings[:i], Bookings.Bookings[i+1:]...)
				}
			}
		}
		Bookings.Mu.Unlock()
		time.Sleep(time.Second)
	}
}

func (em *ExecutionManager) executeBooking(booking Booking) {
	// start execution
	// create the yaml that describes the pod : filename, path/url to Loki
	exec_method := os.Getenv("MONITOR_METHOD")
	logger := oclib.GetLogger()
	if exec_method == "k8s" {
		logger.Error().Msg("TODO : executing oc-monitor in a k8s")
	} else {
		logger.Debug().Msg("Executing oc-monitor localy")
		monitor := LocalMonitor{
			Logger:  logger,
			LokiURL: conf.GetConfig().LokiUrl, KubeURL: "localhost",
			WorkflowName: booking.Workflow,
		}
		monitor.LaunchLocalMonitor()
	}
}
