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;

import java.net.InetSocketAddress;


/**
 * created by swp on 2017/8/21
 * 适配器，用于匹配数据模板与数据处理器
 *
 * @author dylan
 */
public class UdpDataStreamAdapter extends DataStreamAdapter {

    private InetSocketAddress socketAddress = null;

    public UdpDataStreamAdapter() {
        super();
    }

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

    @Override
    public void pushData(ByteBuf buf, ChannelHandlerContext cx, DatagramPacket datagramPacket) {
        try {
            this.ctx = cx;
            this.socketAddress = new InetSocketAddress(datagramPacket.sender().getAddress(), datagramPacket.sender().getPort());
            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 + " UdpDataStreamAdapter 接收到数据 " + " ip:" + socketAddress.getHostName() + " port:" + socketAddress.getPort() + " " + BytesUtil.byte2HexStr(block));
            }
        } catch (IndexOutOfBoundsException e) {
            LogHelper.error(this.adapterKey, e);
        }
    }

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

    }


}
