package view

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

type TemplateNoCache struct {
	ext string
	dir string
}

func NewTemplateNoCache(dir, ext string) (*TemplateNoCache, error) {
	if dir == "" {
		return nil, errors.New("dir argument is required")
	}
	if ext == "" {
		return nil, errors.New("ext argument is required")
	}
	s := &TemplateNoCache{
		ext: ext,
		dir: dir,
	}
	return s, nil
}

func (s *TemplateNoCache) Render(w io.Writer, name string, data any) (err error) {
	cache, err := template.New("").Funcs(funcs).ParseGlob(
		fmt.Sprintf("%s/*.%s", s.dir, s.ext),
	)
	if err != nil {
		return fmt.Errorf("ParseGlob: %s", err)
	}
	name = fmt.Sprintf("%s.%s", name, s.ext)
	err = cache.ExecuteTemplate(w, name, data)
	if err != nil {
		return fmt.Errorf("ExecuteTemplate(%s): %s", name, err)
	}
	return
}
