package daemons

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

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

var Executions = ScheduledExecution{Execs: []*workflow_execution.WorkflowExecution{}}

type ExecutionManager struct{}

// Loop every second on the Execution's list and move the Execution 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 executions", len(Executions.Execs))
		Executions.Mu.Lock()
		if len(Executions.Execs) > 0 {
			executions := Executions.Execs
			for i := len(executions) - 1; i >= 0; i-- {
				if executions[i].ExecDate.Before(time.Now().UTC()) {
					logger.Info().Msg("Will execute " + executions[i].UUID + " soon")
					go em.executeExecution(executions[i])
					Executions.Execs = append(executions[:i], executions[i+1:]...)
				}
			}
		}
		Executions.Mu.Unlock()
		time.Sleep(time.Second)
	}
}

func (em *ExecutionManager) executeExecution(Execution *workflow_execution.WorkflowExecution) {
	// start execution
	// create the yaml that describes the pod : filename, path/url to Loki
	var executor Executor
	// exec_method := os.Getenv("MONITOR_METHOD")
	logger := oclib.GetLogger()
	duration := 0
	if Execution.EndDate != nil {
		duration = int(Execution.EndDate.Sub(Execution.ExecDate).Seconds())
	}

	if conf.GetConfig().Mode == "local" {
		executor = NewLocalMonitor(Execution.ExecutionsID, Execution.CreatorID, duration)
	}

	if conf.GetConfig().Mode == "container" {
		executor = NewContainerMonitor(Execution.ExecutionsID, Execution.CreatorID, duration)
	}

	if executor == nil {
		logger.Fatal().Msg("Could not create logger")
	}
	args := executor.PrepareMonitorExec()
	executor.LaunchMonitor(args,logger)

	// 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 Execution.EndDate != nil {
	// 		duration = int(Execution.EndDate.Sub(Execution.ExecDate).Seconds())
	// 	}
	// 	monitor := LocalMonitor{
	// 		Logger:      	logger,
	// 		Duration:    	duration,
	// 		ExecutionID: 	Execution.ExecutionsID,
	// 		PeerID:     	Execution.CreatorID,
	// 		LokiUrl:		conf.GetConfig().LokiUrl,
			
	// 	}
	// 	monitor.LaunchLocalMonitor()
	// }
}
