package webserver

import (
	"log"
	"net/http"
	"path"
	"text/template"

	"git.tovijaeschke.xyz/tovi/personal_website/database"
	"git.tovijaeschke.xyz/tovi/personal_website/helper"
)

type Unauthenticated struct {
	FlashMsg string
}

var (
	partials = []string{
		"html/header.gohtml",
		"html/sidebar.gohtml",
		"html/index-intro.gohtml",
		"html/index-links.gohtml",
		"html/index-post-list.gohtml",
		"html/post-list.gohtml",
		"html/post.gohtml",
		"html/error.gohtml",
	}
)

func ServeTemplate(w http.ResponseWriter, r *http.Request, mainFile string, v map[string]interface{}) {
	var (
		tpl   *template.Template
		files []string
		e     error
	)

	if _, ok := v["Subject"]; !ok {
		v["Subject"] = ""
	}

	v["LastUpdatedAt"], e = database.GetLastUpdatedAt()
	if e != nil {
		v["LastUpdatedAt"] = " - "
	}

	v["SidebarLinks"], e = database.GetAllSidebarLinks()
	if e != nil {
		log.Println(e)
		http.Redirect(w, r, "/error", 302)
		return
	}

	files = []string{webRootJoin(mainFile)}
	for _, p := range partials {
		files = append(files, webRootJoin(p))
	}

	tpl, e = template.New(path.Base(files[0])).Funcs(
		template.FuncMap{
			"FormatTimestamp": helper.FormatTimestamp,
			"MinusInt64":      helper.MinusInt64,
			"MinusInt":        helper.MinusInt,
			"Minus":           helper.MinusInt,
			"PlusInt64":       helper.PlusInt64,
			"PlusInt":         helper.PlusInt,
			"Iterate":         helper.Iterate,
			"StrToLower":      helper.StrToLower,
		},
	).ParseFiles(files...)
	if e != nil {
		log.Println(e)
		http.Redirect(w, r, "/error", 302)
	}

	w.Header().Set("Content-type", "text/html")
	e = tpl.Execute(w, v)
	if e != nil {
		log.Println(e)
		http.Redirect(w, r, "/error", 302)
		return
	}
}
