package ws

import (
	"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/gobuffalo/packr/v2"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

// InitServer instanciate the main echo instance
func (ws *WS) InitServer() (err error) {
	ws.e = echo.New()
	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},
	}))

	ws.templatesbox = packr.New("templates", "../../templates")
	ws.staticbox = packr.New("static", "../../static")

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

	return
}

// RunServer runs the webserver
func (ws *WS) RunServer(config config.Config) (err error) {
	ws.InitServer()

	ws.e.GET("/", ws.Page.Index)
	ws.e.GET("/static/*", func(c echo.Context) error {
		return static.GetStatic(ws.staticbox, c)
	})
	ws.e.GET("/json", ws.Page.JSON)
	ws.e.OPTIONS("/", echo.MethodNotAllowedHandler)

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

type WS struct {
	Page         Page
	e            *echo.Echo
	templatesbox *packr.Box
	staticbox    *packr.Box
}
