package view

import (
	"errors"
	"fmt"
	"html/template"
	"io"
)

type TemplateCache struct {
	cache *template.Template
	ext   string
}

func NewTemplateCache(dir, ext string) (*TemplateCache, error) {
	if dir == "" {
		return nil, errors.New("dir argument is required\n")
	}
	if ext == "" {
		return nil, errors.New("ext argument is required\n")
	}
	cache, err := template.New("").Funcs(funcs).ParseGlob(
		fmt.Sprintf("%s/*.%s", dir, ext),
	)
	if err != nil {
		return nil, fmt.Errorf("ParseGlob: %s", err)
	}
	s := &TemplateCache{
		cache: cache,
		ext:   ext,
	}
	return s, nil
}

func (s *TemplateCache) Render(w io.Writer, name string, data any) (err error) {
	name = fmt.Sprintf("%s.%s", name, s.ext)
	t := s.cache.Lookup(name)
	if t == nil {
		return fmt.Errorf("unknown template: %s", name)
	}
	err = t.Execute(w, data)
	if err != nil {
		return fmt.Errorf("Execute: %s", err)
	}
	return
}
