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 *DpsClientManager) DpsWebSocketStart() {

	for {
		log.Println("<---监听管道通信--->")
		select {
		case conn := <-DpsManager.Register: // 建立连接
			log.Printf("建立新连接: %v", conn.DpConversations.Uid)
			DpsManager.Clients[utils.Strval(conn.DpConversations.Uid)] = conn
			replyMsg := &DpsReplyMsg{
				Code:    e.WebsocketSuccess,
				Content: "已连接至服务器",
			}
			fmt.Println("Manager.Clients: ", DpsManager.Clients)
			//这里调用记忆文件方法

			msg, _ := json.Marshal(replyMsg)
			_ = conn.Socket.WriteMessage(websocket.TextMessage, msg)

		case conn := <-DpsManager.Unregister: // 断开连接
			log.Printf("连接失败:%v", conn.DpConversations.Uid)
			if _, ok := Manager.Clients[utils.Strval(conn.DpConversations.Uid)]; ok {
				replyMsg := &DpsReplyMsg{
					Code:    e.WebsocketEnd,
					Content: "连接已断开",
				}
				msg, _ := json.Marshal(replyMsg)
				_ = conn.Socket.WriteMessage(websocket.TextMessage, msg)
				//if conn.Send != nil {
				//	close(conn.Send)
				//}

				delete(DpsManager.Clients, utils.Strval(conn.DpConversations.Uid))
			}
			//广播信息

		}
		//
	}
}
