package org.jim.server.command.handler;

import org.jim.common.ImAio;
import org.jim.common.ImPacket;
import org.jim.common.packets.ChatType;
import org.jim.common.packets.Command;
import org.jim.common.packets.InputIndicatorReqBody;
import org.jim.common.packets.RespBody;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.util.InputIndicatorKit;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;

/**
 * 输入指示器 (正在输入)
 * @author Darren
 * @date 2020/2/13 17:47
 */
public class IMInputIndicatorReqHandler extends AbstractCmdHandler {

    @Override
    public Command command() {
        return Command.COMMAND_INPUT_POINTER_REQ;
    }

    /**
     *{
     *   'from':String来源ID,
     *   'group_id':String群组id仅在chatType为1时需要,
     *   'chatType':Integer聊天类型{0:未知,1:群聊,2:私聊}
     *}
     * @param packet
     * @param channelContext
     * @return {@link {@link ImPacket}}
     * @author Darren
     * @date 2020/2/13 20:22
     */
    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {
        if( null == packet.getBody() ){
            Aio.remove(channelContext, "body is null");
            return null;
        }
        InputIndicatorReqBody reqBody = InputIndicatorKit.toInputIndicatorReqBody(packet.getBody());
        if( reqBody == null ){
            ImPacket respChatPacket = InputIndicatorKit.dataInCorrectRespPacket(channelContext);
            return respChatPacket;
        }
        ImPacket inputIndicatorPacket = new ImPacket(Command.COMMAND_INPUT_POINTER_REQ,new RespBody(Command.COMMAND_INPUT_POINTER_REQ, reqBody).toByte());
        inputIndicatorPacket.setSynSeq(packet.getSynSeq());
        if(ChatType.CHAT_TYPE_PUBLIC.getNumber() == reqBody.getChatType()){
            String group_id = reqBody.getGroup_id();
            //告知 群组 对方正在输入
            ImAio.sendToGroup(group_id, inputIndicatorPacket);
            //发送成功响应包
            return InputIndicatorKit.sendSuccessRespPacket(channelContext);
        }
        return null;
    }

}
