package got

import (
	"text/template"

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

var (
	implementStmtsTmpl *template.Template
	implementStmtsErr  error
)

func init() {

	implementStmtsTmpl, implementStmtsErr = ParseTemplate(`
	{{if .preconditions}}
		if _, err = executeAction(
			ctx,
			{{.preconditions}},
		); err != nil {
			return
		}
	{{end}}
	return
	`)

	if implementStmtsErr != nil {
		panic(implementStmtsErr)
	}
}

var (
	GenImplement = &Middleware{
		Id:   "implement",
		Type: "method",
		Fn: func(ctx *MiddlewareContext) error {
			var (
				method  = ctx.Method
				context = map[string]interface{}{
					"preconditions": parseMethodActions(method.Preconditions),
				}
			)
			// Nome do metodo que verifica se a entidade tem dependencias
			out, _ := TemplateToString(implementStmtsTmpl, context)
			ctx.Statement.Block(G.Id(out)).Line()

			return nil
		},
	}
)
