package socketserver

import (
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/websocket/v2"
	"github.com/rs/zerolog/log"
	"lms.de/backend/modules/structs"
)

func WebSocketServer(app *fiber.App) {
	app.Get("/ws", websocket.New(func(c *websocket.Conn) {
		defer func() {
			unregister <- c
			c.Close()
		}()

		register <- &structs.SocketClient{Conn: c}

		for {
			messageType, msg, err := c.ReadMessage()

			if err != nil {
				if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
					log.Error().Msgf("Read err: %s", err)
				}

				return
			}

			if messageType == websocket.TextMessage {
				broadcast <- structs.SocketMessage{Conn: c, Msg: msg}
			} else {
				log.Error().Msgf("websocket message received of type %v", messageType)
			}
		}
	}))
}
