package com.imdroid.sideslope.server.tcp;

import com.imdroid.common.util.DataTypeUtil;
import com.imdroid.sideslope.executor.BizExecutors;
import com.imdroid.sideslope.executor.MessageParser;
import com.imdroid.sideslope.message.BaseMessage;
import com.imdroid.sideslope.server.OnlineChannels;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@ChannelHandler.Sharable
@Component
public class RtcmTcpHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private final Logger logger = LoggerFactory.getLogger(RtcmTcpServer.class);
    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf src) throws Exception{
        if (logger.isDebugEnabled()) {
            byte[] data = new byte[src.readableBytes()];
            src.getBytes(0, data);
            logger.debug("receive message:" + DataTypeUtil.getHexString(data));
        }
        try {
            BaseMessage message = MessageParser.instance.parse(src);
            OnlineChannels.INSTANCE.updateConfigChannel(message.getId(), ctx.channel(), null);
            BizExecutors.execute(message);
        }
        catch (Exception e){

        }
    }
/*
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state() == IdleState.READER_IDLE) {
                Channel channel = ctx.channel();
                logger.info(channel.remoteAddress() + " idle too long to be closed");
                channel.close();
            }
        }
    }
*/
    @Override
    public void channelInactive(ChannelHandlerContext ctx)
            throws Exception {
        logger.info("channel inactive");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}