package templates

import (
	"embed"
	"fmt"
	"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("Cache-Control", "max-age=172800")
	return t.templates.ExecuteTemplate(w, name, data)
}

// BuildTemplates converts packr packages to html/template
func BuildTemplates(fs *embed.FS) (builttemplates *Template, err error) {
	basedir := "templates"
	tmpl := template.New(basedir)

	dir, err := fs.ReadDir(basedir)
	if err != nil {
		log.Println(err)
	}
	for _, filename := range dir {
		tmplContent, err := fs.ReadFile(fmt.Sprintf("%s/%s", basedir, filename.Name()))
		if err != nil {
			log.Println(err)
		}
		tmpl.New(filename.Name()).Parse(string(tmplContent))
	}

	builttemplate := &Template{
		templates: tmpl,
	}

	return builttemplate, nil
}

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