package httpserver

import (
	"fmt"
	"html/template"
	"io/fs"
	"log"
	"net/http"
)

type TemplateRenderer struct {
	templatesFS fs.FS
}

func NewTemplateRenderer(templatesFS fs.FS) *TemplateRenderer {
	return &TemplateRenderer{
		templatesFS: templatesFS,
	}
}

func (r *TemplateRenderer) Render(w http.ResponseWriter, templatePath string, data interface{}) {
	tmpl, err := template.ParseFS(r.templatesFS, fmt.Sprintf("templates/%s", templatePath), "templates/layout.html")
	if err != nil {
		InternalServerError(w, nil)
		log.Printf("failed to parse template %s: %v", templatePath, err)

		return
	}

	err = tmpl.Execute(w, data)
	if err != nil {
		InternalServerError(w, nil)
		log.Printf("failed to execute template %s: %v", templatePath, err)

		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
}
