package got

import (
	"fmt"
	"os"
	"strings"

	. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
	G "github.com/dave/jennifer/jen"
	"github.com/davecgh/go-spew/spew"
)

func generateHookCall(project *Project, method *Method, hookId string) {
	if !method.Hook(hookId) {
		return
	}

	path := fmt.Sprintf(
		"../project/include/go/hook_%s_%s_%s_gen.go",
		// project.OutPath,
		// project.Package,
		method.Entity,
		method.ID,
		hookId,
	)

	// return
	if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {

		methodId := fmt.Sprintf(
			"%s%s%s",
			strings.Title(hookId),
			method.Entity,
			strings.Title(method.ID),
		)

		fmt.Println("\n\n\nCREATE HOOK", path, methodId)

		file := G.NewFile(project.Package)
		file.Func().Id(methodId).Call(
			G.Id("ctx").Qual(IRIS_CTX, "Context"),
			G.Id("resp").Interface(),
		).Op("*").Qual(API_ERROR, "Error").Block(
			G.Return(G.Nil()),
		)

		if err := Write(path, file); err != nil {
			spew.Dump(err)
		}
	}
}

func parseMethodActions(actions []Action) string {
	actionsCallStmt := []string{}
	var actionStmt, actionId string

	for _, action := range actions {
		actionId = strings.Title(action.ID)
		actionStmt = fmt.Sprintf("actions.%s", actionId)

		if action.Context != nil {
			actionStmt = fmt.Sprintf(
				"%s(%s)",
				actionStmt,
				fmt.Sprintf("%#v", action.Context),
			)
		}

		actionsCallStmt = append(
			actionsCallStmt, 
			fmt.Sprintf(`{"%s", %s}`, actionId,actionStmt),
		)
	}

	if len(actionsCallStmt) > 0{
		return fmt.Sprintf(`[]Action {
			%s,
			}`, strings.Join(actionsCallStmt, ",\n"))
	}
	return ""

}

func getCustom(options map[string]interface{}, path string, fallback ...interface{}) (resp interface{}) {
	found := false
	if options != nil  {
		if resp, found = options[path]; found {
			return
		}
	} 
	for _, value := range fallback {
		resp = value
	}
	return
}
