package daemons

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

	"github.com/rs/zerolog"
)

type LocalMonitor struct {
	ExecutionID string
	PeerID      string
	Duration    int
	LokiUrl		string
	MongoUrl	string
	DBName		string

}

func NewLocalMonitor(executionsId string, peerId string, duration int) (Executor){
	return &LocalMonitor{
		ExecutionID: executionsId,
		PeerID: peerId,
		Duration: duration,
		LokiUrl: conf.GetConfig().LokiUrl,
		MongoUrl: conf.GetConfig().MongoUrl,
		DBName: conf.GetConfig().DBName,
	}
}

// func (lm *LocalMonitor) LaunchLocalMonitor() {
// 	if lm.ExecutionID == "" {
// 		lm.Logger.Error().Msg("Missing parameter in LocalMonitor")
// 	}

// }

func (lm *LocalMonitor) PrepareMonitorExec() []string {

	args := []string{
		"-e", lm.ExecutionID,
		"-p", lm.PeerID,
		"-u", lm.LokiUrl,
		"-m", lm.MongoUrl,
		"-d", lm.DBName,
	}


	if lm.Duration > 0 {
		args = append(args, "-t", fmt.Sprintf("%d", lm.Duration))
	}

	return args
}

func (lm *LocalMonitor) LaunchMonitor(args []string, l zerolog.Logger)  {
	cmd := exec.Command(conf.GetConfig().MonitorPath, args...)
	fmt.Printf("Command : %v\n", cmd)

	stdoutMonitord, err := cmd.StdoutPipe()
	if err != nil {
		l.Error().Msg("Could not retrieve stdoutpipe for execution of oc-monitord" + err.Error())
	}

	err = cmd.Start()
	if err != nil {
		l.Error().Msg("Could not start oc-monitor for " + lm.ExecutionID + " : " + err.Error())
	}

	logExecution(stdoutMonitord, l)
}