package controllers

import (
	"fmt"
	"log"
	"net/http"
	"wss/models"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var proxy *models.MqttServerOrWs
var (
	Fd      = uint32(1) // 连接唯一标识
	mclient = models.MqttClientZ{}
)

type WsServer struct {
}

func (ggg WsServer) Get(ctx *gin.Context) {
	upgrader := websocket.Upgrader{
		WriteBufferSize: 1024,
		ReadBufferSize:  1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	// 升级为WebSocket连接
	conn, err := upgrader.Upgrade(ctx.Writer, ctx.Request, http.Header{"Sec-WebSocket-Protocol": []string{"mqtt"}})
	if err != nil {
		log.Printf("WebSocket升级失败: %v", err)
		return
	}
	// 注册新连接
	fmt.Println("升级为WebSocket连接成功")
	proxy = models.NewMqttServerOrWs(conn, Fd, mclient)
	models.RWlock.Lock()
	fmt.Println(Fd)
	models.WsConnetPool[Fd] = proxy
	Fd++
	models.RWlock.Unlock()
	log.Printf("客户端已连接: Fd=%d", proxy.Fd)
	// 设置关闭处理函数
	conn.SetCloseHandler(func(code int, text string) error {
		log.Printf("客户端已断开连接: Fd=%d", proxy.Fd)
		fmt.Println(models.WsConnetPool)
		if wsClient, exists := models.WsConnetPool[proxy.Fd]; exists {
			if wsClient.Client != nil {
				wsClient.Client.Close()
			}
			delete(models.WsConnetPool, proxy.Fd)

		}
		fmt.Println("WsConnetPool", models.WsConnetPool)
		return nil
	})

	go proxy.HandleMessages() // 读取并处理MQTT控制报文
}
