package cn.estsh.i3plus.ext.mes.pcn.apiservice.util.reader;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

/**
 * @author ns
 * @create 2021/11/29 0029 下午 15:16
 */
public class NettyConnect {

    private final EventLoopGroup group = new NioEventLoopGroup();

    private final Bootstrap bootstrap = new Bootstrap();

    public final static String QUESTION = "我想听个笑话";

    public boolean connect() {
        try {
            bootstrap.group(group)
                    /*由于我们用的是UDP协议，所以要用NioDatagramChannel来创建*/
                    .channel(NioDatagramChannel.class)
                    .handler(new ResponseHandler());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void shutDown() {
        group.shutdownGracefully();
    }

    public void sendCommand(){}

    public void listTags(){}

    public void readTag(byte tagID){

    }

    public void writeTag(){}

    public void run(int port) throws Exception {

//        EventLoopGroup group = new NioEventLoopGroup();
        try {
//            Bootstrap b = new Bootstrap();
//            b.group(group)
//                    /*由于我们用的是UDP协议，所以要用NioDatagramChannel来创建*/
//                    .channel(NioDatagramChannel.class)
//                    .handler(new ResponseHandler());
            //不需要建立连接
            connect();
            Channel ch = bootstrap.bind(0).sync().channel();
            //将UDP请求的报文以DatagramPacket打包发送给接受端
            byte[] chTemp = new byte[]{0x40, 0x0c, (byte) 0xec, 0x01, (byte) 0xcb, (byte) 0x9f,0x03,0x00,0x01,0x00,0x00,0x00,0x00,0x59};

            ByteBuffer bb = ByteBuffer.allocate(chTemp.length);
            bb.put(chTemp);
            bb.flip();
            ChannelFuture future = ch.writeAndFlush(
                    new DatagramPacket(
//                            Unpooled.wrappedBuffer(bb),
                            Unpooled.wrappedBuffer(chTemp),
                            new InetSocketAddress("192.168.31.100",
                                    port)))
                    .sync();
            System.out.println(future.get());
            //不知道接收端能否收到报文，也不知道能否收到接收端的应答报文
            // 所以等待15秒后，不再等待，关闭通信
            if (!ch.closeFuture().await(15000)) {
                System.out.println("查询超时！");
            }
        } catch (Exception e) {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int answerPort = ReaderConstWords.DEFAULT_PORT;

        new NettyConnect().run(answerPort);
    }
}
