package web

import (
	"embed"
	"fmt"
	"io/fs"
	"net/http"

	"git.ctrlz.es/mgdelacroix/craban/api"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
	"github.com/rs/zerolog/log"
)

//go:embed static/*
var staticFS embed.FS
var indexBytes []byte

func init() {
	indexBytes, _ = staticFS.ReadFile("static/index.html")
}

type WebServer struct {
	*http.Server
}

func NewWebServer(port int) (*WebServer, error) {
	s := &WebServer{
		&http.Server{Addr: fmt.Sprintf(":%d", port)},
	}

	return s, nil
}

func (w *WebServer) RegisterRoutes(api *api.API) {
	r := mux.NewRouter()
	apiRouter := r.PathPrefix("/api").Subrouter()

	apiRouter.HandleFunc("/login", api.Login).Methods("POST")
	apiRouter.HandleFunc("/users", api.Secured(api.CreateUser)).Methods("POST")
	apiRouter.HandleFunc("/games", api.Secured(api.CreateGame)).Methods("POST")
	apiRouter.HandleFunc("/games", api.Secured(api.ListGames)).Methods("GET")

	staticFSSub, _ := fs.Sub(staticFS, "static")
	staticFSHandler := StaticFSHandler{http.FileServer(http.FS(staticFSSub))}
	r.PathPrefix("/").Handler(staticFSHandler)

	// setup CORS only in the API subrouter?
	originsOK := handlers.AllowedOrigins([]string{"*"})
	methodsOK := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})

	w.Server.Handler = handlers.CORS(originsOK, methodsOK)(r)
}

func (w *WebServer) Start() error {
	log.Debug().Msg("starting webserver")
	if err := w.Server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		return err
	}
	return nil
}

func (w *WebServer) Close() error {
	log.Debug().Msg("closing webserver")
	return w.Server.Close()
}
