package com.cn.processor;

import org.jim.common.ImAio;
import org.jim.common.ImPacket;
import org.jim.common.http.HttpConst;
import org.jim.common.http.HttpRequest;
import org.jim.common.packets.Command;
import org.jim.common.packets.LoginReqBody;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.LoginReqHandler;
import org.jim.server.command.handler.processor.handshake.WsHandshakeProcessor;
import org.tio.core.ChannelContext;

import java.util.Map;

/**
 * 握手处理器
 * @author Darren
 * @date 2020/2/2 10:05
 */
public class IMChatWsHandshakeProcessor extends WsHandshakeProcessor {

    /**
     * 三次握手之后处理的操作
     * @param packet
     * @param channelContext
     * @return {@link }
     * @author Darren
     * @date 2020/2/2 10:09
     */
    @Override
    public void onAfterHandshaked(ImPacket packet, ChannelContext channelContext) throws Exception {

        LoginReqHandler loginReqHandler = (LoginReqHandler)CommandManager.getCommand(Command.COMMAND_LOGIN_REQ);
        //获取参数
        HttpRequest request = (HttpRequest)packet;
        Map<String, Object[]> paramMap = request.getParams();
        //请求token
        String token = paramMap.get("token") == null ? null : (String)paramMap.get("token")[0];
        LoginReqBody loginReqBody = new LoginReqBody(token);
        byte[] loginBytes = JsonKit.toJsonBytes(loginReqBody);
        request.setBody(loginBytes);
        request.setBodyString(new String(loginBytes, HttpConst.CHARSET_NAME));
        //调用登录请求处理器,处理数据 返回登录详细数据包
        ImPacket loginRespPacket = loginReqHandler.handler(request, channelContext);
        if( loginRespPacket != null ){
            //通知对应客户端 发送响应结果
            ImAio.send(channelContext,loginRespPacket);
        }
    }
}
