package view

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

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

func NewTemplateInFS(fsys fs.FS, dir, ext string) (*TemplateInFS, error) {
	if dir == "" {
		return nil, errors.New("dir argument is required")
	}
	if ext == "" {
		return nil, errors.New("ext argument is required")
	}
	cache, err := template.New("").Funcs(funcs).ParseFS(fsys,
		fmt.Sprintf("%s/*.%s", dir, ext),
	)
	if err != nil {
		return nil, fmt.Errorf("ParseGlob: %s", err)
	}
	s := &TemplateInFS{
		cache: cache,
		ext:   ext,
	}
	return s, nil
}

func (s *TemplateInFS) 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
}
