/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package app

import (
	"net/http"

	"dev.tandem.ws/tandem/camper/pkg/auth"
	"dev.tandem.ws/tandem/camper/pkg/campsite"
	"dev.tandem.ws/tandem/camper/pkg/database"
	httplib "dev.tandem.ws/tandem/camper/pkg/http"
	"dev.tandem.ws/tandem/camper/pkg/template"
)

type publicHandler struct {
	campsite *campsite.PublicHandler
}

func newPublicHandler() *publicHandler {
	return &publicHandler{
		campsite: campsite.NewPublicHandler(),
	}
}

func (h *publicHandler) Handler(user *auth.User, company *auth.Company, conn *database.Conn) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var head string
		head, r.URL.Path = httplib.ShiftPath(r.URL.Path)
		switch head {
		case "":
			home := newHomePage()
			home.MustRender(w, r, user, company, conn)
		case "campsites":
			h.campsite.Handler(user, company, conn).ServeHTTP(w, r)
		default:
			http.NotFound(w, r)
		}
	})
}

type homePage struct {
	*template.PublicPage
}

func newHomePage() *homePage {
	return &homePage{template.NewPublicPage()}
}

func (p *homePage) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	p.Setup(r, user, company, conn)
	template.MustRenderPublic(w, r, user, company, "home.gohtml", p)
}
