package org.ts.ddcs.dataStream;

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;
import lombok.extern.slf4j.Slf4j;


/**
 * created by swp on 2017/8/21
 * 适配器，用于连接网络通道与数据处理器
 *
 * @author dylan
 */
@Slf4j
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()) {
                            log.info("{} tcp writeAndFlush is successful", adapterKey);
                        } else {
                            //记录错误
                            log.error("{} tcp writeAndFlush is error {}", adapterKey, channelFuture.cause().getMessage());
                        }
                    }
                });
            } catch (Exception e) {
                log.error(this.getClass().getName(), e);
            } finally {
                log.info("{} tcp writeAndFlush to rtuCode {}", adapterKey, rtuCode);
            }
        } else {
            log.info("{} tcp net channel close", adapterKey);
        }
    }

    @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.readEvent(this);
            }
        } catch (IndexOutOfBoundsException e) {
            log.error(this.adapterKey, e);
        }
    }
}
