package main

import (
	// External
	we "git.gibonuddevalla.se/go/wrappederror"

	// Standard
	"fmt"
	"net/http"
	"unicode"
	"unicode/utf8"
)

type Page struct {
	LAYOUT string
	PAGE   string
	MENU   string
	CONFIG map[string]string
	Label  string
	Icon   string

	Data any
}

func (p *Page) Render(w http.ResponseWriter) {
	tmpl, err := getPage(p.LAYOUT, p.PAGE)
	if err != nil {
		httpError(w, we.Wrap(err).Log())
		return
	}

	if p.Icon == "" {
		p.Icon = p.PAGE
	}

	if p.Label == "" {
		r, _ := utf8.DecodeRuneInString(p.PAGE)
		titled := unicode.ToTitle(r)
		p.Label = fmt.Sprintf("%s%s", string(titled), p.PAGE[1:len(p.PAGE)])
	}

	if p.MENU == "" {
		p.MENU = p.PAGE
	}

	data := map[string]any{
		"VERSION": VERSION,
		"LAYOUT":  p.LAYOUT,
		"PAGE":    p.PAGE,
		"MENU":    p.MENU,
		"CONFIG":  smonConfig.Settings,

		"Label":   p.Label,
		"Icon":    p.Icon,
		"Data":    p.Data,
	}

	err = tmpl.Execute(w, data)
	if err != nil {
		httpError(w, we.Wrap(err).Log())
	}
}
