package http

import (
	"net/http"
	"strings"

	"source.toby3d.me/toby3d/home/internal/common"
	"source.toby3d.me/toby3d/home/internal/domain"
	"source.toby3d.me/toby3d/home/internal/theme"
)

type Handler struct {
	themes theme.UseCase
}

func NewHandler(themes theme.UseCase) *Handler {
	return &Handler{
		themes: themes,
	}
}

func (h *Handler) Handle(site *domain.Site, entry *domain.Entry) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// TODO(toby3d): handle home page.
		// TODO(toby3d): handle sections.
		// TODO(toby3d): handle errors.

		// NOTE(toby3d): wrap founded entry into theme template and
		// answer to client.
		contentLanguage := make([]string, len(entry.Translations))
		for i := range entry.Translations {
			contentLanguage[i] = entry.Translations[i].Language.Code()
		}

		w.Header().Set(common.HeaderContentLanguage, strings.Join(contentLanguage, ", "))

		template, err := h.themes.Do(r.Context(), site, entry)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)

			return
		}

		w.Header().Set(common.HeaderContentType, common.MIMETextHTMLCharsetUTF8)
		if err = template(w); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}
