package router

import (
	"fmt"

	"git.kocoder.xyz/kocoded/szuntis-backend/middleware"
	"github.com/gofiber/contrib/websocket"
	"github.com/gofiber/fiber/v2"
)

type WebSocketRouter struct {
}

func NewWebSocketRouter(authMiddleware middleware.WsMiddleware, ws fiber.Router) error {
	router := &WebSocketRouter{}
	go RunHub()
	ws.Get("/", func(c *fiber.Ctx) error {
		return c.SendFile("/home/kocoder/szuntis-viel-zu-fiel/szuntis-backend/router/home.html", true)
	})
	ws.Get("/ws", authMiddleware.IsWebscoketUpgrade, websocket.New(router.Upgrade))
	return nil
}

type Client struct{}

var Clients = make(map[*websocket.Conn]Client)
var Register = make(chan *websocket.Conn)
var Broadcast = make(chan string)
var Unregister = make(chan *websocket.Conn)

func RunHub() {
	for {
		select {
		case conn := <-Register:
			Clients[conn] = Client{}
			fmt.Println("Connection registered")
		case message := <-Broadcast:
			fmt.Println("Recieved BC request: " + message)
			for connection := range Clients {
				if err := connection.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
					fmt.Println("Write error: ", err)

					Unregister <- connection
					connection.WriteMessage(websocket.CloseMessage, []byte{})
					connection.Close()
				}
			}
		case connection := <-Unregister:
			delete(Clients, connection)
			fmt.Println("Unregistered Connection")
		}
	}
}

func (ws WebSocketRouter) Upgrade(c *websocket.Conn) {
	defer func() {
		fmt.Println(1)
		Unregister <- c
		c.Close()
	}()

	fmt.Println(2)
	Register <- c
	fmt.Println(12)

	for {
		messageType, message, err := c.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
				fmt.Println("Read error: ", err)
			}
			fmt.Println("ASDF")
			return //Call defered function to close the connection
		}

		if messageType == websocket.TextMessage {
			fmt.Println("Messgae", string(message))
			Broadcast <- string(message)
		} else {
			fmt.Println("Websocket message received of type: ", messageType)
		}
	}
}
