package got

import (
	"fmt"
	"text/template"

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

var (
	environmentStmtsTmpl *template.Template
	environmentStmtsErr  error
)

func init() {

	environmentStmtsTmpl, environmentStmtsErr = ParseTemplate(`

	import (
		"fmt"
		common "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
		"os"
	)
	
	const (
		{{range .variables}} Env{{.CamelID}} = "{{.ID}}"
		{{end}}
	)

	func InitEnvironment() error {
		var (
			value     string
			variables = []common.EnvironmentVariable{
				{{range .variables}}{
					ID:          Env{{.CamelID}},
					Description: "{{.Description}}",
					Required:    {{.Required}},
					Default:     "{{.Default}}",
				},{{end}}
			}
		)
	
		for _, variable := range variables {
			if value = os.Getenv(variable.ID); value == "" {
				if variable.Default == "" && variable.Required {
					panic(fmt.Errorf("Environment Variable '%s' not defined! %s", variable.ID, variable.Description))
				}
				value = variable.Default
			}
			common.Setenv(variable.ID, value)
		}
		fmt.Println("Environment...")
		for _, pair := range os.Environ() {
			fmt.Printf("\t├ %s\n",pair)
		}
		return nil
	}`)
}

func CreateEnvironment(p *Project) error {

	for id, environment := range p.Environment {
		environment.CamelID = UnderToCamel(id)
	}

	var (
		context = map[string]interface{}{
			"variables": p.Environment,
		}
	)

	out, _ := TemplateToString(environmentStmtsTmpl, context)

	file := G.NewFile(p.Package)

	file.Id(out)

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