package minecraft

import (
	"github.com/gofiber/websocket/v2"
	"krakatoa.net/backend/modules/cache"
	"krakatoa.net/backend/modules/kraProtocol"
	"krakatoa.net/backend/modules/logger"
	"krakatoa.net/backend/modules/structs"
	serverCommunication "krakatoa.net/backend/serverCommunication"
)

var register = make(chan *websocket.Conn)
var broadcast = make(chan structs.SocketBroadcastData)
var unregister = make(chan *websocket.Conn)

func RunHub() {
	for {
		select {
		case connection := <-register:
			servername := connection.Query("s")

			cache.MinecraftClients[servername] = &structs.MinecraftClient{Name: servername, Connection: connection}

			logger.Minecraft.Debugln("connection registered ", connection.Query("c"), connection)

		case data := <-broadcast:
			logger.Minecraft.Debugln("message received", data.Msg)

			status, cmdID, dest, playerUuid, cmdNumber, args := kraProtocol.DecodeJavaMessage(data.Msg)

			serverCommunication.HandleMinecraftMessage(data.Conn, status, cmdID, dest, playerUuid, cmdNumber, args)

		case connection := <-unregister:
			for servername, client := range cache.MinecraftClients {
				if client.Connection == connection {
					delete(cache.MinecraftClients, servername)
					logger.Minecraft.Debugln("connection unregistered", servername, connection.Query("s"))
				}
			}
		}
	}
}
