package got

import (
	"fmt"

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

func CreateVariables(p *Project) error {

	var (
		varList            = G.Statement{}
		constList          = G.Statement{}
		filterFunctionList = G.Statement{}
		dbid, collectionid string
	)

	// file := G.NewFile(p.Package)
	file := G.NewFile("models")

	for _, entity := range p.Schemas {
		if entity.Type == "object" {

			dbid = fmt.Sprintf("%sDataBase", entity.ID)
			collectionid = fmt.Sprintf("%sCollection", entity.ID)

			constList = append(constList, G.Id(dbid).Op("=").Lit(entity.DB))
			constList = append(constList, G.Id(collectionid).Op("=").Lit(entity.Collection))

			filterFunctionList = append(filterFunctionList, G.Id(`
			func `).Id(
				fmt.Sprintf("Filter%sOptions", entity.ID),
			).Params(
				G.Id("ctx").Qual(IRIS_CTX, "Context"),
			).Id(` *`).Qual(API_URL, "Filter").Id(`{
				var (
					options = &api.Filter{
						DB:`).Id(dbid).Id(`,
						Collection:`).Id(collectionid).Id(`,
					}
				)
				
				if ctx != nil {
					options.Context = ctx
					options.SessionContext = api.GetSessionContext(ctx)
				}

				return options
			} 
			`).Line())

		}
	}

	file.Const().Defs(constList...).Line()

	for id, v1 := range p.Variables {
		varList = append(varList, G.Id(id).Op("=").Lit(v1))
	}

	file.Var().Defs(varList...).Line()

	file.Add(filterFunctionList...)

	return Write(fmt.Sprintf("%s/%s/models/variables_gen.go", p.OutPath, p.Package), file)
}

// ctx, _ = `).Qual("context", "WithTimeout").Call(
// 	G.Qual("context", "Background()"),
// 	G.Lit(30).Op("*").Qual("time", "Second"),
// ).Id(`
