package com.wdkl.ncs.s433.transbox.tcp;

import android.util.Log;

import com.wdkl.ncs.s433.transbox.common.Constants;
import com.wdkl.ncs.s433.transbox.utils.AlarmMessageUtil;

import org.greenrobot.eventbus.EventBus;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

@ChannelHandler.Sharable
public class TcpClientHandler extends SimpleChannelInboundHandler<String> {
    private String TAG = TcpClientHandler.class.getSimpleName();

    private  ChannelHandlerContext ctx;

    //连接断开变量
    public static Boolean connected = false;

    //连接成功执行的方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.ctx = ctx;
        connected = true;

        TcpModel connectModel = new TcpModel();
        connectModel.setType(TcpType.DEVICE);
        connectModel.setAction(TcpAction.DeviceAction.CONNECT);
        connectModel.setData(Constants.MAC_ADDR);
        TcpClient.getInstance().sendMsg(connectModel.toJson());

        Constants.TCP_CONNCETED=true;
        EventBus.getDefault().post(new EventBusModel(Constants.EVENT_TCP_STATE, Constants.TCP_CONNCETED));
    }

    //断开连接
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        connected = false;
        System.out.println("TcpClientHandler 失去连接");
        Constants.TCP_CONNCETED=false;
        EventBus.getDefault().post(new EventBusModel(Constants.EVENT_TCP_STATE, Constants.TCP_CONNCETED));
        TcpClient.getInstance().doConnect();
    }

    //读取String消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String source) throws Exception {
        try {
            System.out.println("TcpClientHandler from server ===> " + source);
            if (source.equals("1")) {
                Log.e(TAG, "收到服务器返回的心跳" + "source " + source);
            } else {
                TcpModel tcpModel = TcpModel.getModelByJson(source);
                EventBus.getDefault().post(new EventBusModel(Constants.EVENT_TCP_MSG, tcpModel));
            }
            ReferenceCountUtil.release(source);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //写心跳包。没有消息发送时，每间隔一定时间会由此方法向服务端发送心跳
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) { //超时未执行写操作,在指定的超时时间内未有写操作，要发送心跳包，告诉服务器连接还存活。服务器收到心跳立马回应，正常客户端收到后执行读操作，
                ctx.writeAndFlush("0");
            } else if (event.state() == IdleState.READER_IDLE) { //认为服务不可用，主动断开连接
                Log.i(TAG, "TcpClientHandler ===> READER_IDLE");
                ctx.close();
            } else if (event.state() == IdleState.ALL_IDLE) {
                Log.i(TAG, "TcpClientHandler ===> ALL_IDLE");
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println("TcpClientHandler 失去连接，错误引起");

        Constants.TCP_CONNCETED=false;
        EventBus.getDefault().post(new EventBusModel(Constants.EVENT_TCP_STATE, Constants.TCP_CONNCETED));
    }

    //发送消息，不直接调用些方法，调用TcpClient中的发送消息
    public void sendMsg(String msg) {
        if (ctx == null) {
            System.out.println("ctx is null");
            return;
        }
        ctx.writeAndFlush(msg);
    }

}
