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

import cn.hutool.core.bean.BeanUtil;
import com.dd.admin.business.chat.domain.ChatVo;
import com.dd.admin.business.chat.entity.Chat;
import com.dd.admin.business.chat.service.ChatService;
import com.dd.admin.business.webSocket.MsgHandlerInterface;
import com.dd.admin.business.webSocket.util.TioUtil;
import com.dd.admin.common.utils.AddressUtils;
import com.dd.admin.common.utils.HttpContext;
import com.dd.admin.common.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.utils.lock.SetWithLock;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.Set;


@Component
@Slf4j
@Service("5")
public class P2PMessageHandler implements MsgHandlerInterface {

    public static P2PMessageHandler handler;

    @Autowired
    ChatService chatService;



    @Override
    public Object handler(Map map, ChannelContext context ){
        Chat chat = BeanUtil.toBean(map, Chat.class);

        chat.setIpAddress(context.getClientNode().getIp());
        chat.setIpRealAddress(AddressUtils.getRealAddress(chat.getIpAddress())); //ip真实地址
        chatService.save(chat);

        ChatVo chatVo = chatService.selectChat(chat.getChatId());

        //t-io支持多点登录,获取的是一个集合,因为此账号可能存在多个连接哦
        SetWithLock<ChannelContext> contexts = Tio.getChannelContextsByUserid(context.getGroupContext(), chat.getToId());
        //用户在线
        if(contexts!=null && contexts.size() > 0) {
            Set<ChannelContext> contextList = contexts.getObj();
            //t-io支持多点登录,获取的是一个集合,向集合发送聊天信息
            for (ChannelContext con : contextList) {
                TioUtil.sendMessage(con, "5", chatVo);
            }
        }

        //也要给我自己发用于数据回显
        //t-io支持多点登录,获取的是一个集合,因为此账号可能存在多个连接哦
        SetWithLock<ChannelContext> contexts1 = Tio.getChannelContextsByUserid(context.getGroupContext(), chat.getFromId());
        //用户在线
        if(contexts1!=null && contexts1.size() > 0) {
            Set<ChannelContext> contextList = contexts1.getObj();
            //t-io支持多点登录,获取的是一个集合,向集合发送聊天信息
            for (ChannelContext con : contextList) {
                TioUtil.sendMessage(con, "5", chatVo);
            }
        }
        return null;
    }}
