package mailadm

import (
	"embed"
	"io/fs"
	"log"
	"net/http"
	"strconv"
	"text/template"

	"go.sour.is/pkg/lg"
)

var (
	//go:embed pages/* layouts/*
	files     embed.FS
	templates map[string]*template.Template
)

type mailadm struct{}

func New() *mailadm {
	return &mailadm{}
}

func (s *mailadm) RegisterHTTP(mux *http.ServeMux) {
	mux.Handle("/mailadm/", lg.Htrace(s, "mailadm"))

	s.loadTemplates()
}
func (s *mailadm) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/mailadm/clicked" {
		templates["edit.go.tpl"].Execute(w, r.URL.Query())
		return
	}

	templates["home.go.tpl"].Execute(w, nil)
}

var funcMap = map[string]any{
	"addone": func(s string) string {
		if i, err := strconv.Atoi(s); err == nil {
			return strconv.Itoa(i + 1)
		}
		return s
	},
}

func (s *mailadm) loadTemplates() error {
	if templates != nil {
		return nil
	}
	templates = make(map[string]*template.Template)
	tmplFiles, err := fs.ReadDir(files, "pages")
	if err != nil {
		return err
	}

	for _, tmpl := range tmplFiles {
		if tmpl.IsDir() {
			continue
		}
		pt := template.New(tmpl.Name())
		pt.Funcs(funcMap)
		pt, err = pt.ParseFS(files, "pages/"+tmpl.Name(), "layouts/*.go.tpl")
		if err != nil {
			log.Println(err)

			return err
		}
		templates[tmpl.Name()] = pt
	}
	return nil
}
