package templates

import (
	"embed"
	"html/template"
	"io"
	"log"
	"strings"

	"github.com/labstack/echo/v4"
)

// Render is a method that render templates
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) (err error) {
	if strings.HasSuffix(name, ".html") {
		c.Response().Header().Set(echo.HeaderContentType, echo.MIMETextHTMLCharsetUTF8)
	}
	c.Response().Header().Add(echo.HeaderCacheControl, "max-age=172800")
	return t.templates.ExecuteTemplate(w, name, data)
}

// BuildTemplates converts embedded files to html/template
func BuildTemplates(templatefiles *embed.FS) (builttemplates *Template, err error) {
	tmpl := template.New("templates")

	folder, err := templatefiles.ReadDir(".")
	for _, filename := range folder {
		content, err := templatefiles.ReadFile(filename.Name())
		if err != nil {
			log.Println(err)
		}
		tmpl.New(filename.Name()).Parse(string(content))
	}

	builttemplates = &Template{
		templates: tmpl,
	}

	return
}

// Template is a template struct
type Template struct {
	templates *template.Template
}
