package routes

import (
	"log"
	"net/http"
	"os"

	"bitbucket.org/imediabrands/oos-service/internal/places"
	"bitbucket.org/imediabrands/oos-service/internal/utils"
	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/julienschmidt/httprouter"
)

// placeTextStore holds the state and city text of the directory sites' state
// and city pages (see InitPlaces).
var placeTextStore *places.Store

// placesCacheControl is the browser/CDN lifetime of a place text answer.
const placesCacheControl = "public, max-age=86400"

// placeTextLicense is the licence of the Wikipedia text the pages show.
const placeTextLicense = "CC BY-SA 4.0"

// InitPlaces loads the place text, places/{st}.json, from where the client
// configs are found: /opt/oos-service/places, else places/ in the checkout.
// Without the directory the pages simply have no place text.
func InitPlaces() {
	dir := "/opt/oos-service/places"
	if _, err := os.Stat(dir); err != nil {
		dir = utils.GetRelativePath() + "places"
	}
	store, err := places.Load(dir)
	if err != nil {
		log.Printf("[ERROR] places: loading %s: %v", dir, err)
	}
	placeTextStore = store
}

type placeTextJSON struct {
	Title      string           `json:"title"`
	Paragraphs []string         `json:"paragraphs"`
	Sections   []places.Section `json:"sections,omitempty"`
	SourceURL  string           `json:"sourceUrl"`
	License    string           `json:"license"`
}

// DataPlacesHandler serves a directory site's place text:
//
//	GET /data/places/{st}             state text: its intro, plus its sections when directory.placeText.state is "full"
//	GET /data/places/{st}/{citySlug}  city text: its intro, when directory.placeText.city is "intro"
//
// 404 not_found when the site shows no such text (placeText off, not a
// directory site) or there is none.
func DataPlacesHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		params := httprouter.ParamsFromContext(req.Context())
		state, city := params.ByName("st"), params.ByName("city")

		var place places.Place
		found := false
		if isDirectorySite(config) {
			settings := directorySettingsFrom(config)
			if city == "" && settings.PlaceTextState != "" {
				place, found = placeTextStore.State(state)
				if settings.PlaceTextState != placeTextFull {
					place.Sections = nil
				}
			} else if city != "" && settings.PlaceTextCity != "" {
				place, found = placeTextStore.City(state, city)
				place.Sections = nil
			}
		}
		if !found {
			w.Header().Set("Cache-Control", listingsCacheControl)
			writeListingsJSON(w, http.StatusNotFound, listingsErrorJSON{Error: "not_found"})
			return
		}
		if place.Title == "" {
			place.Title = place.Name
		}
		w.Header().Set("Cache-Control", placesCacheControl)
		writeListingsJSON(w, http.StatusOK, placeTextJSON{
			Title:      place.Title,
			Paragraphs: place.Intro,
			Sections:   place.Sections,
			SourceURL:  place.SourceURL,
			License:    placeTextLicense,
		})
	})
}
