package views

import (
	"bytes"
	"encoding/json"
	"html/template"
	"net/http"
)

type Renderer struct {
	tpl *template.Template
}

func NewRenderer(pattern string) (*Renderer, error) {
	tpl, err := template.New("ui").Funcs(template.FuncMap{
		"prettyJSON": prettyJSON,
	}).ParseGlob(pattern)
	if err != nil {
		return nil, err
	}
	return &Renderer{tpl: tpl}, nil
}

func (r *Renderer) Render(w http.ResponseWriter, name string, data any) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := r.tpl.ExecuteTemplate(w, name, data); err != nil {
		http.Error(w, "template rendering failed", http.StatusInternalServerError)
	}
}

func prettyJSON(raw []byte) string {
	if len(raw) == 0 {
		return ""
	}
	var out bytes.Buffer
	if err := json.Indent(&out, raw, "", "  "); err != nil {
		return string(raw)
	}
	return out.String()
}
