package routes

import (
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"os"

	"bitbucket.org/imediabrands/oos-service/middlewares"
)

type singleCubeProps struct {
	StartContentServiceOrigin string `json:"startContentServiceOrigin,omitempty"`
	LocationServiceOrigin     string `json:"locationServiceOrigin,omitempty"`
	PortalStaticOrigin        string `json:"portalStaticOrigin,omitempty"`
	Category                  string `json:"category,omitempty"`
	SiteId                    string `json:"siteId,omitempty"`
	TesseractClient           string `json:"tesseractClient,omitempty"`
	DisplayName               string `json:"displayName,omitempty"`
	GaId                      string `json:"gaId,omitempty"`
}

type templateVars struct {
	PageTitle              string
	MetaDescription        string
	MetaKeywords           string
	MetaAuthor             string
	MetaRobots             string
	OgSiteName             string
	OgLocale               string
	OgTitle                string
	OgDescription          string
	OgImage                string
	OgImageAlt             string
	OgImageWidth           string
	OgImageHeight          string
	OgImageType            string
	OgType                 string
	ArticlePublishedTime   string
	ArticleSection         string
	TwitterCard            string
	TwitterTitle           string
	TwitterDescription     string
	TwitterImage           string
	DNSPrefetch            []string
	CanonicalUrl           string
	FaviconUrl             string
	TesseractCdnUrl        string
	TesseractClient        string
	SingleCubeComponent    string
	SingleCubeProps        template.JS
	OverrideConfig         template.JS
	ThemeCSS               template.CSS
	HeadbidAffId           string
	Stylesheets            []string
	DeviceType             string
	Environment            string
	TsuahComment           template.HTML
	GaId                   string
	GaGtm                  string
	GaCx                   string
	GtmId                  string
	GoogleCsa              bool
	GoogleSiteVerification string
	GoogleAdsenseAccount   string
	OrganizationSchema     template.JS
	WebsiteSchema          template.JS
	BreadcrumbSchema       template.JS
	WebPageSchema          template.JS
	ArticleSchema          template.JS
}

func HomepageRouteHandler() http.Handler {
	// Load templates
	tpl := pageTemplates()

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()
		config := middlewares.GetClientConfig(ctx)
		if config == nil {
			http.Error(w, "client config not found", http.StatusInternalServerError)
			return
		}

		displayName := config.GetString("displayName")
		siteId := config.GetString("siteId")
		ga := gaSettingsFromConfig(config)
		tesseractClient := config.GetString("tesseractClient")
		tesseractCdnUrl := config.GetString("tesseract_cdn_url")
		portalStaticCdnUrl := config.GetString("portal_static_cdn_url")
		scsUrl := config.GetString("scs_url")

		if tesseractCdnUrl == "" {
			tesseractCdnUrl = "/static/tesseract"
		}

		hostname, _ := os.Hostname()
		deviceType := "\"desktop\""
		environment := "\"" + config.GetString("environment") + "\""

		// Build props for SingleCube component
		props := singleCubeProps{
			StartContentServiceOrigin: scsUrl,
			PortalStaticOrigin:        portalStaticCdnUrl,
			SiteId:                    siteId,
			Category:                  "homepage",
			TesseractClient:           tesseractClient,
			DisplayName:               displayName,
			GaId:                      ga.GaId,
		}
		propsJSON, _ := json.Marshal(props)

		// Build override config
		overrideConfig := map[string]interface{}{
			"siteId":             siteId,
			"displayName":        displayName,
			"seoMeta":            config.GetStringMap("seoMeta"),
			"logoUrl":            logoURLFromConfig(config),
			"articleTitleSuffix": articleTitleSuffixFromConfig(config),
		}
		configJSON, _ := json.Marshal(overrideConfig)

		pageTitle, metaDescription := pageMetaOverride(config, "home", displayName, "Homepage")

		vars := &templateVars{
			PageTitle:              pageTitle,
			MetaDescription:        metaDescription,
			OgTitle:                pageTitle,
			OgDescription:          metaDescription,
			TwitterTitle:           pageTitle,
			TwitterDescription:     metaDescription,
			FaviconUrl:             faviconURLFromConfig(config),
			DNSPrefetch:            []string{tesseractCdnUrl, scsUrl, portalStaticCdnUrl},
			CanonicalUrl:           canonicalURL(req),
			TesseractCdnUrl:        tesseractCdnUrl,
			TesseractClient:        tesseractClient,
			SingleCubeComponent:    "\"singlecube.Home\"",
			SingleCubeProps:        template.JS(string(propsJSON)),
			OverrideConfig:         template.JS(string(configJSON)),
			DeviceType:             deviceType,
			Environment:            environment,
			TsuahComment:           template.HTML(fmt.Sprintf("<!-- TSUAH: %s -->", hostname)),
			GaId:                   ga.GaId,
			GaGtm:                  ga.GaGtm,
			GaCx:                   ga.GaCx,
			GtmId:                  ga.GtmId,
			GoogleCsa:              ga.GoogleCsa,
			GoogleSiteVerification: googleSiteVerificationFromConfig(config),
		}
		applyMetaRobots(w, vars, req, metaRobotsIndexable)
		applyClientUI(vars, config)
		applyHomepageStructuredData(vars, config, req)
		applyOgDefaults(vars, config)

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}
