package gophertype

import (
	"net/http"

	"git.kirsle.net/apps/gophertype/pkg/authentication"
	"git.kirsle.net/apps/gophertype/pkg/console"
	"git.kirsle.net/apps/gophertype/pkg/controllers"
	"git.kirsle.net/apps/gophertype/pkg/glue"
	"git.kirsle.net/apps/gophertype/pkg/middleware"
	"git.kirsle.net/apps/gophertype/pkg/session"
	"github.com/gorilla/mux"
)

// SetupRouter sets up the HTTP router.
func (s *Site) SetupRouter() error {
	router := mux.NewRouter()

	router.Use(session.Middleware)
	router.Use(authentication.Middleware)
	router.Use(middleware.CSRF)
	router.Use(middleware.AgeGate)

	console.Debug("Setting up HTTP Router")
	for _, route := range glue.GetControllers() {
		console.Debug("Register: %+v", route)
		if len(route.Methods) == 0 {
			route.Methods = []string{"GET"}
		}

		route.Methods = append(route.Methods, "HEAD")

		if len(route.Middleware) > 0 {
			console.Debug("%+v has middlewares!", route)

			handler := route.Middleware[0](http.HandlerFunc(route.Handler))
			router.Handle(route.Path, handler).Methods(route.Methods...)
		} else {
			router.HandleFunc(route.Path, route.Handler).Methods(route.Methods...)
		}
	}

	router.PathPrefix("/").HandlerFunc(controllers.CatchAllHandler)
	router.NotFoundHandler = http.HandlerFunc(controllers.CatchAllHandler)

	console.Debug("Walk the mux.Router:")
	router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
		tpl, err1 := route.GetPathTemplate()
		met, err2 := route.GetMethods()
		console.Debug("path:%s  methods:%s   path-err:%s   met-err:%s", tpl, met, err1, err2)
		return nil
	})

	s.mux = router
	s.n.UseHandler(router)

	return nil
}
