package  org.ts.ddcs.dataStream;

import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.util.BytesUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;


/**
 * created by swp on 2017/8/21
 * 适配器，用于连接网络通道与数据处理器
 *
 * @author dylan
 */
public class TcpDataStreamAdapter extends DataStreamAdapter {

    public TcpDataStreamAdapter() {
        super();
    }

    @Override
    public void output(byte[] respBody) {
        if (null != this.ctx) {
            try {
                ByteBuf buf = Unpooled.buffer(respBody.length);
                buf.writeBytes(respBody);
                ChannelFuture cf = this.ctx.writeAndFlush(buf);
                cf.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        //写操作完成，并没有错误发生
                        if (channelFuture.isSuccess()) {
                            LogHelper.info(adapterKey+" TcpDataStreamAdapter  writeAndFlush is successful!!");
                        } else {
                            //记录错误
                            LogHelper.info(adapterKey+" TcpDataStreamAdapter  writeAndFlush is error!!");
                            LogHelper.error(channelFuture.cause().getMessage());
                        }
                    }
                });
            } catch (Exception e) {
                LogHelper.error(e);
            } finally {
                LogHelper.info(this.adapterKey +" TcpDataStreamAdapter  writeAndFlush to rtuCode:" + rtuCode);
            }
        } else {
            LogHelper.info(this.adapterKey+" TcpDataStreamAdapter  net channel close !!");
        }
    }

    @Override
    public void pushData(ByteBuf buf, ChannelHandlerContext cx, DatagramPacket datagramPacket) {

    }

    @Override
    public void pushData(ByteBuf buf, ChannelHandlerContext cx) {
        try {
            this.ctx = cx;
            int byteSize = buf.readableBytes();
            if (byteSize > 0) {
                byte[] block = new byte[byteSize];
                buf.readBytes(block);
               // this.blockQueue.offer(block);
              //  DataStreamManageHolder.newInstance().dataStreamManager.sourceEvent(this.adapterKey,System.currentTimeMillis());
               DataStreamManageHolder.newInstance().dataStreamManager.sourceEvent(this.adapterKey,block);
               // LogHelper.info(this.adapterKey + " TcpDataStreamAdapter  接收到数据 "+ BytesUtil.byte2HexStr(block));
            }
        } catch (IndexOutOfBoundsException e) {
            LogHelper.error(this.adapterKey, e);
        }
    }
}
