package resthome

import (
	"context"
	"errors"
	"fmt"
	"net/http"

	"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
	"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/pages"
)

func (h *Handler) home(w http.ResponseWriter, r *http.Request) {
	pageHeaders, err := h.src.GetPages(r.Context())
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	h.r.Render(r.Context(), w, r, pages.Home(pageHeaders))
}

func (h *Handler) page(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	uid := r.PathValue("uid")

	page, err := h.src.GetPage(r.Context(), uid)
	if err != nil {
		if errors.Is(err, context.Canceled) {
			w.WriteHeader(http.StatusRequestTimeout)
		}

		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	for i, image := range page.Images {
		if i > 3 {
			break
		}
		ctx = templer.AppendHeader(ctx, fmt.Sprintf(`<link rel="preload" href="%s" as="image" />`, image.Src))
	}

	ctx = templer.PageTitle(ctx, page.Title)

	h.r.Render(ctx, w, r, pages.ContentPage(page))
}
