package server

import (
	"fmt"
	"path/filepath"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/rs/zerolog/log"
	"github.com/ziflex/lecho/v3"
)

type WebServer struct {
	router              *echo.Echo
	webAppDirectoryPath string
	port                string
}

func (r *WebServer) Initialize() {
	r.router = echo.New()
	r.router.HideBanner = true
	//r.router.HidePort = true
	r.router.Logger = lecho.From(log.Logger)
	r.router.Static("/", "www/dist")
	r.router.Use(SetContentType)
	r.router.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
		Format: "${time_rfc3339} ${method} ${uri} status ${status}\n",
	}))
	r.router.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins: []string{"http://localhost:*", "https://localhost:*"},
		AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
	}))
}

func SetContentType(next echo.HandlerFunc) echo.HandlerFunc {
	return func(context echo.Context) error {
		request := context.Request()
		path := request.URL.Path
		extension := filepath.Ext(path)
		if extension == ".jsx" {
			context.Response().Header().Set("Content-Type", "text/javascript")
		}
		return next(context)
	}
}

func (r *WebServer) Start() error {
	err := r.router.Start(fmt.Sprintf(":%s", r.port))
	if err != nil {
		return err
	}
	log.Info().Msgf("web server started on port %s", r.port)
	return nil
}

func (r *WebServer) Close() {
	r.router.Close()
}

func (r *WebServer) SetWebAppDirectoryPath(DirectoryPath string) {
	r.webAppDirectoryPath = DirectoryPath
}

func (r *WebServer) SetPort(Port string) {
	r.port = Port
}

func (r WebServer) Router() *echo.Echo {
	return r.router
}

func SendError(statusCode int, context echo.Context, message string) {
	log.Info().Msg(message)
	responseData := struct {
		Error string `json:"error"`
	}{
		Error: message,
	}
	context.JSON(statusCode, responseData)
}
