package service

import (
	//"chat/conf"
	"WorldEpcho/src/config/e"
	"WorldEpcho/src/utils"
	"encoding/json"
	"fmt"
	_ "fmt"
	//"github.com/gin-gonic/gin/binding"

	"github.com/gorilla/websocket"
	"log"
)

func (manager *WorldClientManager) WorldWebSocketStart() {
	for {
		log.Println("<---监听管道通信--->")
		select {
		case conn := <-WorldManager.Register: // 建立连接
			log.Printf("建立新连接: %v", conn.WorldConversations.Uid)
			if conn == nil || conn.Socket == nil {
				log.Printf("无效的连接或socket为空")
				continue // Skip this iteration if connection or socket is nil
			}
			WorldManager.Client[utils.Strval(conn.WorldConversations.Uid)] = conn
			replyMsg := &WorldReplyMsg{
				StatusCode: e.SUCCESS,
				Code:       e.WebsocketSuccess,
				Content:    "已连接至服务器",
			}
			fmt.Println("WorldManager.Client: ", WorldManager.Client)
			msg, err := json.Marshal(replyMsg)
			if err != nil {
				log.Printf("消息序列化失败: %v", err)
				continue
			}
			err = conn.Socket.WriteMessage(websocket.TextMessage, msg)
			if err != nil {
				log.Printf("消息发送失败: %v", err)
				continue
			}

		case conn := <-WorldManager.Unregister: // 断开连接
			log.Printf("连接失败:%v", conn.WorldConversations.Uid)
			if conn == nil || conn.Socket == nil {
				log.Printf("无效的连接或socket为空")
				continue // Skip this iteration if connection or socket is nil
			}
			if _, ok := WorldManager.Client[utils.Strval(conn.WorldConversations.Uid)]; ok {
				replyMsg := &WorldReplyMsg{
					Code:    e.WebsocketEnd,
					Content: "连接已断开",
				}
				msg, err := json.Marshal(replyMsg)
				if err != nil {
					log.Printf("消息序列化失败: %v", err)
					continue
				}
				err = conn.Socket.WriteMessage(websocket.TextMessage, msg)
				if err != nil {
					log.Printf("消息发送失败: %v", err)
					continue
				}
				delete(WorldManager.Client, utils.Strval(conn.WorldConversations.Uid))
			}
		}
	}
}
