package workflow_builder

import (
	"errors"
	"fmt"

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

type WorflowDB struct {
	Workflow *workflow.Workflow
}

// Create the obj!ects from the mxgraphxml stored in the workflow given as a parameter
func (w *WorflowDB) LoadFrom(workflow_id string) error {
	var err error
	if w.Workflow, err = w.getWorkflow(workflow_id); err != nil {
		return err
	}
	return nil
}

// Use oclib to retrieve the graph contained in the workflow referenced
func (w *WorflowDB) getWorkflow(workflow_id string) (workflow *workflow.Workflow, err error) {
	logger := oclib.GetLogger()

	lib_data := oclib.LoadOne(oclib.LibDataEnum(oclib.WORKFLOW), workflow_id)
	if lib_data.Code != 200 {
		logger.Error().Msg("Error loading the graph")
		return workflow, errors.New(lib_data.Err)
	}

	new_wf := lib_data.ToWorkflow()
	if new_wf == nil {
		logger.Error().Msg("WorflowDB object is empty for " + workflow_id)
		return workflow, errors.New("WorflowDB can't be empty")
	}
	return new_wf, nil
}

func (w *WorflowDB) ExportToArgo(timeout int) (string, error) {
	logger := oclib.GetLogger()

	if len(w.Workflow.Name) == 0 || w.Workflow.Graph == nil {
		return "", fmt.Errorf("can't export a graph that has not been loaded yet")
	}

	argo_builder := ArgoBuilder{graph: *w.Workflow.Graph, Timeout: timeout}
	filename, err := argo_builder.CreateDAG()
	if err != nil {
		logger.Error().Msg("Could not create the argo file for " + w.Workflow.Name)
		return "", err
	}
	return filename, nil
}

// TODO implement this function
func (w *WorflowDB) ExportToHelm(id string) error {
	return nil
}
