package util

import (
	"net/http"
	"amuz.es/go/wiki/bind/template"
	"github.com/flosch/pongo2"
	"github.com/gin-gonic/gin/render"
)

// RenderOptions is used to configure the renderer.
type RenderOptions struct {
	ContentType string
}

// Pongo2Render is a custom Gin template renderer using Pongo2.
type Pongo2Render struct {
	Options  *RenderOptions
	Template *pongo2.Template
	Context  pongo2.Context
}

// New creates a new Pongo2Render instance with custom Options.
func New(options RenderOptions) *Pongo2Render {
	return &Pongo2Render{
		Options: &options,
	}
}

// Default creates a Pongo2Render instance with default options.
func Default() *Pongo2Render {
	return New(RenderOptions{
		ContentType: "text/html; charset=utf-8",
	})
}

// Instance should return a new Pongo2Render struct per request and prepare
// the template by either loading it from disk or using pongo2's cache.
func (p Pongo2Render) Instance(name string, data interface{}) render.Render {
	var templateResult *pongo2.Template
	// always read template files from disk if in debug mode, use cache otherwise.
	//if gin.Mode() == "debug" {Render
	//	template = pongo2.Must(pongo2.FromFile(filename))
	//} else {
	//	template = pongo2.Must(pongo2.FromCache(filename))
	//}
	templateContent:=template.MustAsset(name)

	templateResult=pongo2.Must(pongo2.FromString(string(templateContent[:])))

	return Pongo2Render{
		Template: templateResult,
		Context:  data.(pongo2.Context),
		Options:  p.Options,
	}
}

// Render should render the template to the response.
func (p Pongo2Render) Render(w http.ResponseWriter) error {
	writeContentType(w, []string{p.Options.ContentType})
	err := p.Template.ExecuteWriter(p.Context, w)
	return err
}

// writeContentType is also in the gin/render package but it has not been made
// pubic so is repeated here, maybe convince the author to make this public.
func writeContentType(w http.ResponseWriter, value []string) {
	header := w.Header()
	if val := header["Content-Type"]; len(val) == 0 {
		header["Content-Type"] = value
	}
}
