package web

import (
	"fmt"
	"html/template"
	"net/http"

	"party.at/party/cmd/party/common"
)

func (web *Web) renderFragment(w http.ResponseWriter, r *http.Request, status int, name string, data interface{}) {
	funcs := template.FuncMap{
		"hasPermission": func(code string) bool {
			return common.GetPermissions(r).Include(code)
		},
		"partyColor": func(code string) string {
			switch code {
			case "V":
				return "#009FE3" // ÖVP turquoise
			case "S":
				return "#E30613" // SPÖ red
			case "F":
				return "#0057A8" // FPÖ blue
			case "N":
				return "#E84188" // NEOS pink
			case "G":
				return "#78A22E" // Grüne green
			default:
				return "#6b7280"
			}
		},
	}
	ts, err := template.New(name).Funcs(funcs).ParseFiles("web/html/" + name + ".frag.tmpl")
	if err != nil {
		web.App.LogError(r, err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(status)
	if err = ts.ExecuteTemplate(w, name, data); err != nil {
		web.App.LogError(r, err)
	}
}

func (web *Web) render(w http.ResponseWriter, r *http.Request, status int, page string, data interface{}) {
	funcs := template.FuncMap{
		"dict": func(pairs ...any) (map[string]any, error) {
			if len(pairs)%2 != 0 {
				return nil, fmt.Errorf("dict requires an even number of arguments")
			}
			m := make(map[string]any, len(pairs)/2)
			for i := 0; i < len(pairs); i += 2 {
				m[fmt.Sprint(pairs[i])] = pairs[i+1]
			}
			return m, nil
		},
		"hasPermission": func(code string) bool {
			return common.GetPermissions(r).Include(code)
		},
	}
	ts, err := template.New("base").Funcs(funcs).ParseFiles(
		"web/html/base.layout.tmpl",
		"web/html/partials.tmpl",
		"web/html/"+page+".page.tmpl",
	)
	if err != nil {
		web.App.LogError(r, err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	w.WriteHeader(status)
	if err = ts.ExecuteTemplate(w, "base", data); err != nil {
		web.App.LogError(r, err)
	}
}
