package com.dd.admin.business.webSocket.util;

import com.alibaba.fastjson.JSON;
import com.dd.admin.business.chat.domain.ChatVo;
import com.dd.admin.business.webSocket.SocketMsg;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.Tio;
import org.tio.utils.lock.SetWithLock;
import org.tio.websocket.common.WsResponse;

import java.util.Set;

public class TioUtil {


    public static WsResponse madeWsResponse(String handlerType, Object body){
        SocketMsg msg = new SocketMsg(handlerType,body);
        String responseMsg = JSON.toJSONString(msg);
        return WsResponse.fromText(responseMsg,"utf-8");
    }

    public static boolean sendMessage(ChannelContext con, String handlerType, Object body){
        WsResponse weResponse = madeWsResponse(handlerType,body);
        return Tio.send(con,weResponse);
    }

    // 封装发送聊天信息给指定用户的方法（根据给定的用户ID发送消息）
    public static void sendChatMessageToUser(GroupContext groupContext, String tioId,String handlerType, Object object) {
        // t-io支持多点登录，获取的是一个集合，因为此账号可能存在多个连接哦
        SetWithLock<ChannelContext> contexts1 = Tio.getChannelContextsByUserid(groupContext, tioId);
        // 用户在线
        if (contexts1!= null && contexts1.size() > 0) {
            Set<ChannelContext> contextList = contexts1.getObj();
            // t-io支持多点登录，获取的是一个集合，向集合发送聊天信息
            for (ChannelContext con : contextList) {
                TioUtil.sendMessage(con, handlerType, object);
            }
        }
    }
}
