package responses

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

	"git.kirsle.net/apps/gophertype/pkg/console"
	"git.kirsle.net/apps/gophertype/pkg/markdown"
)

// RenderTemplate renders a Go HTML template.
// The io.Writer can be an http.ResponseWriter.
func RenderTemplate(w io.Writer, r *http.Request, tmpl string, vars interface{}) error {
	if vars == nil {
		vars = NewTemplateVars(w, r)
	}

	// Look for the built-in template.
	b, err := GetFile(tmpl)
	if err == nil {
		t, err := template.New(tmpl).Funcs(TemplateFuncs(r)).Parse(string(b))
		if err != nil {
			console.Error("RenderTemplate: bundled template '%s': %s", tmpl, err)
			return err
		}

		// We found the template. Can we find the layout html?
		if layout, err := GetFile(".layout.gohtml"); err == nil {
			_, err := t.New("layout").Parse(string(layout))
			if err != nil {
				console.Error("RenderTemplate(.layout.gohtml): %s", err)
			}
		} else {
			console.Error("RenderTemplate: .layout.gohtml not found to wrap %s", tmpl)
		}

		console.Debug("Render Templ: %s", tmpl)
		if err := t.ExecuteTemplate(w, "layout", vars); err != nil {
			console.Error("RenderTemplate(%s): %s", tmpl, err)
		}
		return nil
	}

	Panic(w, http.StatusInternalServerError, err.Error())
	return nil
}

// RenderMarkdown renders a Markdown page in the layout template.
func RenderMarkdown(w io.Writer, r *http.Request, tmpl string) error {
	vars := NewTemplateVars(w, r)

	b, err := GetFile(tmpl)
	if err == nil {
		body := string(b)
		title, _ := markdown.TitleFromMarkdown(body)
		vars.V["title"] = title
		vars.V["markdown"] = template.HTML(markdown.RenderTrustedMarkdown(body))
		RenderTemplate(w, r, "_builtin/markdown.gohtml", vars)
		return nil
	}

	Panic(w, http.StatusInternalServerError, err.Error())
	return nil
}

// PartialTemplate renders a partial HTML template.
func PartialTemplate(w io.Writer, r *http.Request, tmpl string, vars interface{}) error {
	if vars == nil {
		vars = NewTemplateVars(w, r)
	}

	// Look for the built-in template.
	b, err := GetFile(tmpl)
	if err == nil {
		t, err := template.New(tmpl).Funcs(TemplateFuncs(r)).Parse(string(b))
		if err != nil {
			console.Error("RenderTemplate: bundled template '%s': %s", tmpl, err)
			return err
		}

		if err := t.ExecuteTemplate(w, tmpl, vars); err != nil {
			console.Error("PartialTemplate(%s): %s", tmpl, err)
		}
		return nil
	}

	Panic(w, http.StatusInternalServerError, err.Error())
	return nil
}
