package tpl

import (
	"bytes"
	"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 {
		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
}