package sse

import (
	"bufio"
	"fmt"
	"jannex/robot-control-manager/modules/cache"
	"jannex/robot-control-manager/modules/config"
	"jannex/robot-control-manager/modules/structs"

	"github.com/gofiber/fiber/v2"
	"github.com/valyala/fasthttp"
)

func SSE(c *fiber.Ctx) error {
	if !config.Cfg.SSEServerEnabled {
		return c.SendStatus(fiber.StatusNotFound)
	}

	c.Set("Content-Type", "text/event-stream")
	c.Set("Cache-Control", "no-cache")
	c.Set("Connection", "keep-alive")
	c.Set("Transfer-Encoding", "chunked")

	c.Context().SetBodyStreamWriter(fasthttp.StreamWriter(func(w *bufio.Writer) {
		var sseclient structs.SSEClient

		sseclient.MessageChannel = make(chan structs.SSEClientChannelMessage)

		cache.AddSSEClient(sseclient)

		for message := range sseclient.MessageChannel {
			fmt.Fprintf(w, "data: %s\n\n", message.Message)

			err := w.Flush()

			if err != nil {
				// Refreshing page in web browser will establish a new
				// SSE connection, but only (the last) one is alive, so
				// dead connections must be closed here.

				for id, sseClient := range cache.GetSSEClients() {
					if id == message.ClientId {
						close(sseClient.MessageChannel)
						cache.DeleteSSEClient(id)
					}
				}
			}
		}
	}))

	return nil
}
