package render

import (
	"net/http"

	"git.ma-al.com/goc_marek/ps_shop/internal/assets"
	"git.ma-al.com/goc_marek/ps_shop/internal/viewmodel"
	"git.ma-al.com/goc_marek/ps_shop/templates"
)

type Engine struct {
	assets assets.Manifest
}

func New(manifest assets.Manifest) *Engine {
	return &Engine{assets: manifest}
}

func (e *Engine) Product(w http.ResponseWriter, r *http.Request, data viewmodel.ProductPageData) error {
	startHTMLStream(w)
	component := templates.ProductPage(data, e.assets.CSSPath("app.css"), e.assets.JSPath("app.js"))
	return component.Render(r.Context(), w)
}

func (e *Engine) Category(w http.ResponseWriter, r *http.Request, data viewmodel.CategoryPageData) error {
	startHTMLStream(w)
	component := templates.CategoryPage(data, e.assets.CSSPath("app.css"), e.assets.JSPath("app.js"))
	return component.Render(r.Context(), w)
}

func startHTMLStream(w http.ResponseWriter) {
	if w == nil {
		return
	}
	headers := w.Header()
	if headers.Get("Content-Type") == "" {
		headers.Set("Content-Type", "text/html; charset=utf-8")
	}
	w.WriteHeader(http.StatusOK)
	if flusher, ok := w.(http.Flusher); ok {
		flusher.Flush()
	}
}
