package daemons

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

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

var Bookings = ScheduledBooking{Bookings: []*workflow_execution.WorkflowExecutions{}}

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 {
		fmt.Println("Checking for bookings", len(Bookings.Bookings))
		Bookings.Mu.Lock()
		if len(Bookings.Bookings) > 0 {
			bookings := Bookings.Bookings
			for i := len(bookings) - 1; i >= 0; i-- {
				if bookings[i].ExecDate.Before(time.Now().UTC()) {
					logger.Info().Msg("Will execute " + bookings[i].UUID + " soon")
					go em.executeBooking(bookings[i])
					Bookings.Bookings = append(bookings[:i], bookings[i+1:]...)
				}
			}
		}
		Bookings.Mu.Unlock()
		time.Sleep(time.Second)
	}
}

func (em *ExecutionManager) executeBooking(booking *workflow_execution.WorkflowExecutions) {
	// 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")
		duration := 0
		if booking.EndDate != nil {
			duration = int(booking.EndDate.Sub(booking.ExecDate).Seconds())
		}
		monitor := LocalMonitor{
			Logger:      logger,
			Duration:    duration,
			LokiURL:     conf.GetConfig().LokiUrl,
			KubeURL:     "localhost",
			ExecutionID: booking.UUID,
			PeerID:      booking.CreatorID,
		}
		monitor.LaunchLocalMonitor()
	}
}