package Webserver

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

	"PersonalWebsite/Database"
	"PersonalWebsite/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
	}
}
