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, peerID string) error {
	logger.Info().Msg("Loading workflow from " + workflow_id)
	var err error
	if w.Workflow, err = w.getWorkflow(workflow_id, peerID); err != nil {
		return err
	}
	return nil
}

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

	lib_data := oclib.NewRequest(oclib.LibDataEnum(oclib.WORKFLOW), "", peerID, []string{}, nil).LoadOne(workflow_id)
	logger.Info().Msg(fmt.Sprint("ERR", lib_data.Code, lib_data.Err))
	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(namespace string, timeout int) (*ArgoBuilder, int, error) {
	logger := oclib.GetLogger()
	logger.Info().Msg(fmt.Sprint("Exporting to Argo", w.Workflow))
	if len(w.Workflow.Name) == 0 || w.Workflow.Graph == nil {
		return nil, 0, fmt.Errorf("can't export a graph that has not been loaded yet")
	}

	argoBuilder := ArgoBuilder{OriginWorkflow: w.Workflow, Timeout: timeout}
	stepMax, _, _, err := argoBuilder.CreateDAG(namespace, true)
	if err != nil {
		logger.Error().Msg("Could not create the argo file for " + w.Workflow.Name)
		return nil, 0, err
	}
	return &argoBuilder, stepMax, nil
}

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