package render

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

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

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

var Include func(req *srv.Req, props Props, funcs Funcs)

func Template(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 {
		props = propFunc[0].(Props)
	}
	if len(propFunc) > 1 {
		funcs = propFunc[1].(Funcs)
	}

	Include(req, props, funcs)

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

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

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

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

	html := buf.String()

	return html
}
