package com.its.pis.xnetudp.thread;

import com.its.pis.xnetudp.codec.CenterCommClientEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;

@Slf4j
@Service
public class CenterCommClientSender {

    @Async("centerCommExecutor")
    public void run(String ip, int port, ByteBuffer sendBuffer) {
        if (sendBuffer == null) {
            log.error("CenterCommClientSender.run: Notify Data NULL");
            return;
        }

        EventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioDatagramChannel.class);
            bootstrap.group(nioEventLoopGroup);
            bootstrap.option(ChannelOption.SO_BROADCAST, false);
            bootstrap.handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel channel) throws Exception
                {
                    channel.pipeline().addLast(new CenterCommClientEncoder(ip, port));
                }
            });

            Channel channel = bootstrap.bind(0).sync().channel();
            ChannelFuture f = channel.writeAndFlush(sendBuffer).sync();
            if (!f.isDone() || !f.isSuccess()) {
                log.error("CenterCommClientSender.run: Send Failed. isDone: {}, isSuccess: {}", f.isDone(), f.isSuccess());
            }
        }
        catch(Exception e) {
            log.error("CenterCommClientSender.run: Exception: {}", e.toString());
            e.printStackTrace();
        }
        finally {
            nioEventLoopGroup.shutdownGracefully();
            log.info("CenterCommClientSender.run: {} Bytes, ip: {}, port: {}", sendBuffer.array().length, ip, port);
        }
    }
}
