package web

import (
	"fmt"
	"html/template"
	"io"

	"gitlab.com/dynaweb/ains-microservices/pkg/i18n"
)

type View struct {
	base  *template.Template
	funcs template.FuncMap
}

type Data struct {
	Lang      string
	Title     string
	Active    string
	User      *UserCtx
	CSRFToken string
}

type UserCtx struct {
	UserID int64
	Role   string
	State  string
	PPD    string
	School string
}

func NewView(translator *i18n.Translator) (*View, error) {
	funcs := template.FuncMap{
		"t": func(lang, key string) string {
			if translator == nil {
				return key
			}
			return translator.T(lang, key)
		},
	}
	base, err := template.New("base").Funcs(funcs).ParseFS(Assets,
		"templates/layouts/*.html",
		"templates/partials/*.html",
	)
	if err != nil {
		return nil, fmt.Errorf("web: parse base templates: %w", err)
	}
	return &View{base: base, funcs: funcs}, nil
}

func (v *View) Render(w io.Writer, status int, page string, data Data) error {
	t, err := v.base.Clone()
	if err != nil {
		return fmt.Errorf("web: clone templates: %w", err)
	}
	if _, err := t.ParseFS(Assets, "templates/pages/"+page+".html"); err != nil {
		return fmt.Errorf("web: parse page %q: %w", page, err)
	}
	return t.ExecuteTemplate(w, "base", data)
}

func (v *View) HasPage(page string) bool {
	_, err := Assets.Open("templates/pages/" + page + ".html")
	return err == nil
}
