package got

import (
	// . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/gen"

	"text/template"

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

var (
	getListStmtsTmpl *template.Template
	getListStmtsErr  error
)

func init() {

	getListStmtsTmpl, getListStmtsErr = ParseTemplate(`
	var (
		// ntoken   string
		// count    = 0
		entities = []*models.{{.entity}}{}
		values = ctx.Values()
	)

	values.Set("entities", &entities)
	
	options := values.Get("$filter").(*api.Filter)
	options.DB = "{{.dbName}}"
	options.Collection = "{{.collectionName}}"
	
	options.Entities = &entities


	if err = t.Fields(options); err != nil {
		return
	}
	
	{{if .preconditions}}
		if _, err = executeAction(
			ctx,
			{{.preconditions}},
		); err != nil {
			return
		}
	{{end}}
	
	if _, err = models.Api.FindMany(options); err != nil {
		return
	}

	{{if .beforeResponse}}
	if resp, err = executeAction(
		ctx,
		{{.beforeResponse}},
	); err != nil || resp != nil {
		return
	}
	{{end}}

	resp = &models.{{.responseStruct}}{
		Itens:              entities,
		NextPageToken:      options.NextPageToken,
		ResultSizeEstimate: options.ResultSizeEstimate,
	}

	return`)

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

var (
	GenGetStmtsList = &Middleware{
		Id:   "get_list",
		Type: "method",
		Fn: func(ctx *MiddlewareContext) error {

			var (
				project        = ctx.Project
				method         = ctx.Method
				responseStruct = method.Response
				response       = project.ResponseEntity(responseStruct)
			)

			if response.IsGeneric {
				GenFromGenericModel(project, response)
				responseStruct = response.NewName
			}

			var (
				context = map[string]interface{}{
					"dbName":         project.GetEntityDB(method.Entity),
					"collectionName": project.GetCollection(method.Entity),
					"beforeSend":     method.Hook("beforeSend"),
					"beforeFind":     method.Hook("beforeFind"),
					"entity":         method.Entity,
					"responseStruct": responseStruct,
					"preconditions":  parseMethodActions(method.Preconditions),
					"beforeResponse": parseMethodActions(method.BeforeResponse),
				}
			)
			// Nome do metodo que verifica se a entidade tem dependencias
			out, _ := TemplateToString(getListStmtsTmpl, context)
			ctx.Statement.Block(G.Id(out)).Line()

			return nil
		},
	}
)
