package templates

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

	"github.com/gobuffalo/packr/v2"
	"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)
	}
	return t.templates.ExecuteTemplate(w, name, data)
}

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

	for _, filename := range box.List() {
		tmplContent, _ := box.FindString(filename)
		tmpl.New(filename).Parse(tmplContent)
	}

	builttemplates = &Template{
		templates: tmpl,
	}

	return
}

/*
// BuildTemplatesDir converts packr packages to html/template
func BuildTemplatesDir(dir string) (builttemplates *Template, err error) {
	tmpl := template.New("templates")

	err = pkger.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		freader, _ := pkger.Open(path)
		tmplContent, err := ioutil.ReadAll(freader)
		tmpl.New(info.Name()).Parse(string(tmplContent))
		fmt.Println(info.Name(), tmplContent)
		return err
	})

	builttemplates = &Template{
		templates: tmpl,
	}

	return
}*/

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