package com.mogo.telematic.client.handler;

import android.util.Log;

import com.mogo.telematic.MogoProtocolMsg;
import com.mogo.telematic.client.NettyTcpClient;
import com.mogo.telematic.client.listener.NettyClientListener;
import com.mogo.telematic.client.status.ConnectState;

import org.jetbrains.annotations.NotNull;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


public class NettyClientHandler extends SimpleChannelInboundHandler<MogoProtocolMsg> {

    private static final String TAG = "NettyClientHandler";
    private NettyClientListener listener;
    private final String mSign;
    private Object heartBeatData;

    public NettyClientHandler(@NotNull NettyClientListener listener, String sign) {
        this.listener = listener;
        this.mSign = sign;
    }

    /**
     * <p>客户端上线</p>
     *
     * @param ctx ChannelHandlerContext
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Log.d(TAG, "channelActive");
        listener.onClientStatusConnectChanged(ConnectState.STATUS_CONNECT_SUCCESS, mSign, ctx.channel());
    }

    /**
     * 客户端收到消息
     *
     * @param ctx ChannelHandlerContext
     * @param msg 消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MogoProtocolMsg msg) throws Exception {
        if (msg.getProtocolType() == MogoProtocolMsg.IDENTITY_REGIST) {
            String sn = new String(msg.getBody());
            synchronized (NettyTcpClient.class) {
                NettyTcpClient.sSERVER_SN = sn;
            }
        } else {
            if (listener != null) {
                listener.onMessageResponseClient(msg, mSign, ctx.channel());
            }
        }
    }
}
