package location

import (
	"dev.tandem.ws/tandem/camper/pkg/auth"
	"dev.tandem.ws/tandem/camper/pkg/database"
	httplib "dev.tandem.ws/tandem/camper/pkg/http"
	"dev.tandem.ws/tandem/camper/pkg/template"
	gotemplate "html/template"
	"net/http"
)

type PublicHandler struct {
}

func NewPublicHandler() *PublicHandler {
	return &PublicHandler{}
}

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 "":
			switch r.Method {
			case http.MethodGet:
				page := newLocationPage()
				page.MustRender(w, r, user, company, conn)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodGet)
			}
		default:
			http.NotFound(w, r)
		}
	})
}

type locationPage struct {
	*template.PublicPage
	Directions gotemplate.HTML
	MapEmbed   gotemplate.HTML
}

func newLocationPage() *locationPage {
	page := &locationPage{
		PublicPage: template.NewPublicPage(),
	}
	return page
}

func (p *locationPage) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	p.Setup(r, user, company, conn)
	row := conn.QueryRow(r.Context(), `
		select coalesce(i18n.directions, location.directions)::text
		     , map_embed::text
		from location
		    left join location_i18n as i18n on location.company_id = i18n.company_id and i18n.lang_tag = $1
		where location.company_id = $2
		`, user.Locale.Language, company.ID)
	if err := row.Scan(&p.Directions, &p.MapEmbed); err != nil {
		if !database.ErrorIsNotFound(err) {
			panic(err)
		}
	}
	template.MustRenderPublic(w, r, user, company, "location.gohtml", p)
}
