package model

import "encoding/json"

func BindPhaseExecDetail(
	base ScriptPhaseExecBase,
	detailJSON []byte,
) (ScriptPhaseExec, error) {
	switch base.GetType() {
	case ScriptPhaseTypeMutate:
		var muts []ScriptMutation
		if err := json.Unmarshal(detailJSON, &muts); err != nil {
			return nil, err
		}
		return &ScriptMutationPhaseExec{
			ScriptPhaseExecBase: base,
			Mutations:           muts,
		}, nil
	case ScriptPhaseTypeProceed:
		return &ScriptProceedPhaseExec{
			ScriptPhaseExecBase: base,
		}, nil
	}
	return nil, nil
}

func parsePhase2PhaseExec(phase ScriptPhase) ScriptPhaseExec {
	switch phase.GetType() {
	case ScriptPhaseTypeMutate:
		return parseMutationPhase(phase)
	case ScriptPhaseTypeProceed:
		return parseProceedPhase(phase)
	}
	return nil
}

func parseMutationPhase(
	phase ScriptPhase,
) ScriptPhaseExec {
	return &ScriptMutationPhaseExec{
		ScriptPhaseExecBase: ScriptPhaseExecBase{
			Name:          phase.GetName(),
			Type:          ScriptPhaseTypeMutate,
			Status:        ExecStatusPending,
			Message:       phase.GetMessage(),
			StartDuration: phase.GetStartDuration(),
		},
		Mutations: phase.GetMutations(),
	}
}

func parseProceedPhase(
	phase ScriptPhase,
) ScriptPhaseExec {
	return &ScriptProceedPhaseExec{
		ScriptPhaseExecBase: ScriptPhaseExecBase{
			Name:          phase.GetName(),
			Type:          ScriptPhaseTypeProceed,
			Message:       phase.GetMessage(),
			Status:        ExecStatusPending,
			StartDuration: phase.GetStartDuration(),
		},
	}
}
