package main

import (
	"context"
	"embed"
	"log"
	"net/http"

	"xengineering.eu/ceres/controller"
	"xengineering.eu/ceres/model"
	"xengineering.eu/ceres/view"

	"github.com/gorilla/mux"
)

type Server http.Server

//go:embed view/static/simple.css/simple.css view/static/ceres.js
var static embed.FS

func NewServer(addr string, db *model.DB) *Server {
	var r *mux.Router = mux.NewRouter()

	r.PathPrefix("/static/").
		Handler(http.StripPrefix("/static/", http.FileServer(http.FS(static))))

	r.HandleFunc("/version", view.VersionRead(version)).Methods(`GET`)

	r.HandleFunc("/recipes", view.RecipesRead(db)).Methods(`GET`)
	r.HandleFunc("/recipe/create", view.RecipeCreate).Methods(`GET`)

	r.HandleFunc("/recipe", controller.RecipeCreate(db)).Methods(`POST`)
	r.HandleFunc("/recipe/{id:[0-9]+}", view.RecipeRead(db)).Methods(`GET`)
	r.HandleFunc("/recipe/{id:[0-9]+}", controller.RecipeUpdate(db)).Methods(`POST`)
	r.HandleFunc("/recipe/{id:[0-9]+}", controller.RecipeDelete(db)).Methods(`DELETE`)

	r.HandleFunc("/favicon.ico", view.FaviconRead).Methods(`GET`)

	r.HandleFunc("/", view.IndexRead).Methods(`GET`)

	muxer := http.NewServeMux()
	muxer.Handle("/", r)

	var srv http.Server
	srv.Addr = addr
	srv.Handler = muxer

	log.Printf("Configured server to listen on http://%s\n", srv.Addr)

	return (*Server)(&srv)
}

func (s *Server) Start() {
	(*http.Server)(s).ListenAndServe()
}

func (s *Server) Stop() {
	err := (*http.Server)(s).Shutdown(context.Background())
	if err != nil {
		log.Printf("Failed to shutdown HTTP server: %v\n", err)
	} else {
		log.Println("Stopped HTTP server")
	}
}