package minecraft

import (
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/websocket/v2"
	"krakatoa.net/backend/modules/configs/serverConfig"
	"krakatoa.net/backend/modules/logger"
	"krakatoa.net/backend/modules/structs"
)

func RunServer() {
	cfg := serverConfig.Cfg.Servers.MinecraftServer

	mcApp := fiber.New(fiber.Config{AppName: "minecraft"})

	mcApp.Use("/ws", func(c *fiber.Ctx) error {
		logger.Minecraft.Infoln("server name", c.Query("s"))

		// check with access key in config
		if c.Query("ak") != cfg.AccessKey {
			return c.SendStatus(fiber.StatusUnauthorized)
		}

		if websocket.IsWebSocketUpgrade(c) { // Returns true if the client requested upgrade to the WebSocket protocol
			return c.Next()
		}
		return c.SendStatus(fiber.StatusUpgradeRequired)
	})

	go RunHub()

	WebSocketServer(mcApp)

	mcApp.Listen(cfg.Host)
}

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

		register <- c

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

			if err != nil {
				if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
					logger.Minecraft.Warnln("read error:", err)
				}
				return
			}

			if messageType == websocket.BinaryMessage {
				broadcast <- structs.SocketBroadcastData{Conn: c, Msg: msg}
			} else {
				logger.Minecraft.Warnln("websocket message received of type", messageType)
			}
		}
	}))
}
