package templates

import (
	"embed"
	"io"
	"io/fs"
	"log"
	"strings"
	"text/template"

	"git.ctdo.de/ctdo/machinelock-manager/template_functions"
)

var (
	Templates *template.Template
	//go:embed templates
	Res embed.FS
)

func init() {
	var err error
	Templates, err = compileTemplates()
	if err != nil {
		log.Fatal(err)
	}
}

func compileTemplates() (*template.Template, error) {
	tpl := template.New("")

	tpl.Funcs(template_functions.FunctionMap)
	err := fs.WalkDir(Res, "templates", func(path string, info fs.DirEntry, err error) error {
		if err != nil {
			log.Fatal(err)
			return nil
		}
		if info.IsDir() || !strings.HasSuffix(path, ".gohtml") {
			return nil
		}
		f, _ := Res.Open(path)
		sl, _ := io.ReadAll(f)
		name := strings.Split(info.Name(), ".")
		tpl.New(name[0]).Parse(string(sl))
		return nil
	})
	return tpl, err
}