package com.inspect.patrol.linkage;

import com.inspect.patrol.linkage.handler.UDPClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
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 java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class NettyUdpClient {
    private static final Logger logger = LoggerFactory.getLogger(NettyUdpClient.class);
    @Value("${patrol.video.netty_udp_client_ip}")
    private String nettyUdpClientIp;
    @Value("${patrol.video.netty_udp_client_port}")
    private String nettyUdpClientPort;
    @Autowired
    private UDPClientHandler udpClientHandler;

    public void sendMessage(List<byte[]> packetSlice) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, Boolean.valueOf(true)).handler(this.udpClientHandler);
        Channel channel = bootstrap.bind(0).sync().channel();

        for (byte[] byteSlice : packetSlice) {
            ByteBuf buffer = Unpooled.buffer(byteSlice.length);
            buffer.writeBytes(byteSlice);
            channel.writeAndFlush(new DatagramPacket(buffer, new InetSocketAddress(this.nettyUdpClientIp, Integer.parseInt(this.nettyUdpClientPort)))).sync().await();
        }

        if (!channel.closeFuture().await(15000L)) {
            System.out.println("out of time");
        }

    }
}
