package got

import (
	"fmt"
	"strings"

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

func CreateMainFile(project *Project) (err error) {

	spew.Dump(project.Custom)

	var (
		Index               = G.NewFile("main")
		address             = strings.Join(strings.Split(project.BaseURL, ":")[1:], ":")
		goPackageRepository = project.Custom["go.package.repository"].(string)
	)

	address = strings.Replace(address, "//", "", -1)

	Index.Id(`import (
	
		`).Id(project.ID).Lit(goPackageRepository+"/build/v1").Id(`
		models `).Lit(goPackageRepository+"/build/v1/models").Id(`
		"git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api" // Pacotes do framework web
		"os"
		"fmt"
		iris "github.com/kataras/iris/v12"
		"github.com/kataras/iris/v12/middleware/recover"
	)

	func main() {

		var (
			err error
		)
	
		if err = `).Id(project.ID).Id(`.InitEnvironment(); err != nil {
			panic(err)
		}

		app := iris.New()
		app.Logger().SetLevel("debug")
		// Optionally, add two built'n handlers
		// that can recover from any http-relative panics
		// and log the requests to the terminal.
		app.Use(recover.New())
		app.Use(`).Qual("github.com/kataras/iris/v12/middleware/logger", "New").Id(`())
		
		app.Use(api.DefaultCorsHandler())
	
		api.BuildVersion = `).Id(fmt.Sprintf(`"%s"`, project.BuildVersion)).Id(`

		// session := &api.Mongo{ Config: os.Getenv("MONGO_CONFIG") }
		models.Api.Config = os.Getenv("MONGO_CONFIG")
	
		if err = models.Api.Init(); err != nil {
			panic(err)
		}
		
		if err = `).Id(fmt.Sprintf("%s.AppInitialize(app)", project.ID)).Id(`; err != nil {
			panic(err)
		}

		`).Id(project.ID).Id(`.Register(app)

		fmt.Println("API_VERSION: ", api.BuildVersion)
		app.Run(iris.Addr(os.Getenv("APP_ADDRS")), iris.WithoutServerError(iris.ErrServerClosed))
	}
	`)

	if err = Write(fmt.Sprintf("%s/main.go", project.OutPath), Index); err != nil {
		return
	}

	// path := fmt.Sprintf("%s/v1/app_initialize.go", project.OutPath)
	path := fmt.Sprintf("../project/include/go/app_initialize.go")

	if !utils.FileExists(path) {

		AppInitialize := G.NewFile("v1")
		AppInitialize.Id(`
		import(
			iris "github.com/kataras/iris/v12"
		)

		func AppInitialize(app *iris.Application) error { 
			return nil
		}
		`)
		if err = Write(path, AppInitialize); err != nil {
			return
		}
	}

	return nil
}

// app.RegisterView(iris.HTML("./public", ".html"))
// app.Get("/", func(ctx iris.Context) {
// 	ctx.View("index.html")
// })
// app.HandleDir("/", "./public", iris.DirOptions{
// 	Asset:      Asset,
// 	AssetInfo:  AssetInfo,
// 	AssetNames: AssetNames,
// 	// IndexName:  "index.html", // default.
// 	// If you want to show a list of embedded files when inside a directory without an index file:
// 	// ShowList:   true,
// 	// DirList: func(ctx iris.Context, dirName string, f http.File) error {
// 	// 	// [Optional, custom code to show the html list].
// 	// }
// })
// app.SPA(app.StaticHandler("./public", false, false))
