package main

import (
	"os"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

type App struct {
	Engine *gin.Engine
	Stream *SseStream
	DB     *DB
}

func InitHttp() *App {

	app := &App{
		Engine: nil,
		Stream: nil,
		DB:     nil,
	}

	app.DB = InitDb(os.Getenv("DB"))
	app.Stream = InitSse()

	app.Engine = gin.Default()
	app.Engine.Use(cors.Default())

	app.RegisterWebRoutes()
	app.RegisterApiRoutes()

	return app
}

func (app *App) Run() {

	port := os.Getenv("PORT")

	if port == "" {
		port = "8080"
	}

	app.Engine.Run(":" + port)
}

func (app *App) RegisterWebRoutes() {

	display := app.Engine.Group("/display")
	display.Static("/", "./static/display")

	priority := app.Engine.Group("/priority")
	priority.Static("/", "./static/priority")

	mobile := app.Engine.Group("/mobile")
	mobile.Static("/", "./static/mobile")

	setup := app.Engine.Group("/setup")
	setup.Static("/", "./static/setup")

	surfers := app.Engine.Group("/surfers")
	surfers.Static("/", "./static/surfers")

	draws := app.Engine.Group("/draws")
	draws.Static("/", "./static/draws")

	sapp := app.Engine.Group("/_app")
	sapp.Static("/", "./static/_app")

	static := app.Engine.Group("/static")
	static.Static("/", "./static/static")

	app.Engine.StaticFile("/", "./static/index.html")
	app.Engine.StaticFile("/favicon.png", "./static/favicon.png")

	app.Engine.ForwardedByClientIP = true
	app.Engine.SetTrustedProxies([]string{"127.0.0.1"})
}

func (app *App) RegisterApiRoutes() {

	api := app.Engine.Group("/api")

	// api.GET("/priority", app.GetPriority)
	// api.POST("/priority", app.SetPriority)

	api.GET("/sse", app.Stream.SseHeadersMiddleware(), app.Stream.Stream)
	api.POST("/msg", app.Stream.SendMsg)
	api.POST("/startheat", app.StartHeatTimer)
	// api.GET("/stopheat", app.StopHeatTimer)
	api.POST("/saveheat", app.SaveHeat)
	api.POST("/deleteheat", app.DeleteHeat)
	api.GET("/loadheats", app.LoadHeats)
	// api.GET("/runningheat", app.LoadRunning)
	api.GET("/loadsurfers", app.LoadSurfers)
	api.POST("/savesurfer", app.SaveSurfer)
	api.POST("/deletesurfer", app.DeleteSurfer)
}
