package controllers

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/spf13/viper"
	"go.fifitido.net/ytdl-web/app"
	"go.fifitido.net/ytdl-web/pkg/htmx"
	"go.fifitido.net/ytdl-web/pkg/server"
	"go.fifitido.net/ytdl-web/pkg/view"
	"go.fifitido.net/ytdl-web/pkg/ytdl"
	"go.fifitido.net/ytdl-web/version"
)

type HomeController struct {
	ytdl ytdl.Ytdl
}

var _ server.Controller = (*HomeController)(nil)

func NewHomeController(ytdl ytdl.Ytdl) *HomeController {
	return &HomeController{
		ytdl: ytdl,
	}
}

func (c *HomeController) Router(r chi.Router) {
	r.Get("/", c.Index)
}

func (c *HomeController) Index(w http.ResponseWriter, r *http.Request) {
	hx := htmx.New(w, r)
	isSecure := r.URL.Scheme == "https"

	if hx.IsHtmxRequest() {
		hx.PushUrl("/")

		app.Views.Render(w, "index", view.Data{
			"BasePath":      viper.GetString("base_path"),
			"Version":       version.Version,
			"Build":         version.Build,
			"BinaryVersion": c.ytdl.Version(),
			"IsSecure":      isSecure,
		})
	} else {
		app.Views.Render(w, "index", view.Data{
			"BasePath":      viper.GetString("base_path"),
			"Version":       version.Version,
			"Build":         version.Build,
			"BinaryVersion": c.ytdl.Version(),
			"IsSecure":      isSecure,
		}, "layouts/main")
	}
}
