package main

import (
	"bytes"
	"io"
	"log"
	"net/http"

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

func (app *App) RegisterApiRoutes() {

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

	api.GET("/sse", app.Stream.SseHeadersMiddleware(), app.Stream.Stream)
	api.GET("/priority", app.GetPriority)
	api.POST("/priority", app.SetPriority)
}

func (app *App) GetPriority(c *gin.Context) {
	c.JSON(http.StatusOK, app.Stream.Data)

	log.Printf("get priority: %+v", app.Stream.Data)
}

func (app *App) SetPriority(c *gin.Context) {
	var priority = Priority{}

	body, _ := io.ReadAll(c.Request.Body)
	log.Printf("set priority body: %s", string(body))
	c.Request.Body = io.NopCloser(bytes.NewReader(body))

	err := c.ShouldBindJSON(&priority)
	log.Printf("set priority: %+v - err: %+v", priority, err)
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": priority,
	})

	var msg = Message{
		Event: "priority",
		Data:  priority,
	}

	app.Stream.Send(msg)

	app.Stream.Data = priority
}
