package ws

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

	"git.paulbsd.com/paulbsd/dip/src/config"
	"git.paulbsd.com/paulbsd/dip/src/static"
	"git.paulbsd.com/paulbsd/dip/src/templates"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

// InitServer instanciate the main echo instance
func (ws *WS) InitServer(templatefiles *embed.FS, staticfiles *embed.FS) (err error) {
	ws.e = echo.New()
	ws.e.Pre(middleware.RemoveTrailingSlash())
	ws.e.HideBanner = true
	ws.e.Use(middleware.GzipWithConfig(middleware.GzipConfig{
		Level: 5,
	}))
	ws.e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{http.MethodGet, http.MethodPut, http.MethodPost, http.MethodDelete},
	}))

	builtTemplates, _ := templates.BuildTemplates(templatefiles)
	ws.e.Renderer = builtTemplates

	return
}

// RunServer runs the webserver
func (ws *WS) RunServer(config config.Config, templatefiles *embed.FS, staticfiles *embed.FS) (err error) {
	ws.InitServer(templatefiles, staticfiles)

	ws.e.GET("/", func(c echo.Context) (err error) {
		ws.Page.Process(c, "")
		return
	})
	ws.e.GET("/:ip", func(c echo.Context) (err error) {
		ws.Page.Process(c, "")
		return
	})
	ws.e.GET("/json", func(c echo.Context) (err error) {
		ws.Page.Process(c, "json")
		return
	})
	ws.e.GET("/json/:ip", func(c echo.Context) (err error) {
		ws.Page.Process(c, "json")
		return
	})
	ws.e.GET("/static/*", func(c echo.Context) (err error) {
		return static.GetStatic(staticfiles, c)
	})

	ws.e.Logger.Fatal(ws.e.Start(fmt.Sprintf("%s:%s", config.Host, config.Port)))
	return
}

type WS struct {
	Page Page
	e    *echo.Echo
}
