package tpl

import (
	"bytes"
	"errors"
	"html/template"
	"path/filepath"
	"strings"

	"git.clearsky.net.au/cody/gex.git/srv"
	"git.clearsky.net.au/cody/gex.git/utils"
)

type Props map[string]any
type Funcs = template.FuncMap

func include(req *srv.Req, props Props, funcs Funcs) {}

var Include = include

func Render(fp string, req *srv.Req, propFunc ...interface{}) string {
	if !strings.Contains(fp, "app/") {
		fp = utils.Cwd(2) + "/" + fp
	}

	fp = strings.Replace(fp, ".tpl", ".gen.tpl", 1)

	var props = Props{}
	var funcs = Funcs{}

	if len(propFunc) > 0 {
		var ok bool
		props, ok = propFunc[0].(Props)
		if !ok {
			err := errors.New("invalid props type passed to Render(), must be map[string]any")
			utils.Err(err)
			return err.Error()
		}
	}

	if len(propFunc) > 1 {
		var ok bool
		funcs, ok = propFunc[1].(Funcs)
		if !ok {
			err := errors.New("invalid funcs type passed to Render(), must be map[string]func (template.funcMap)")
			utils.Err(err)
			return err.Error()
		}
	}

	props["Req"] = req

	Include(req, props, funcs)

	tmpl, err := template.
		New(filepath.Base(fp)).
		Funcs(funcs).
		ParseFiles(fp)

	if err != nil {
		utils.Err(err)
		return err.Error()
	}

	var buf bytes.Buffer
	err = tmpl.Execute(&buf, props)

	if err != nil {
		utils.Err(err)
		return err.Error()
	}

	html := buf.String()

	return html
}