package com.jsowell.netty.server.mqtt;

import com.jsowell.common.constant.Constants;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Slf4j
@Component
@Order(5)
public class MqttSever implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        InetSocketAddress address = new InetSocketAddress(Constants.SOCKET_IP, 1883);
        // this.start(address);
    }

    public void start(InetSocketAddress address) {
        // log.info("========NettyServer.start  order 1");
        //配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap mqttBootstrap = new ServerBootstrap();
            mqttBootstrap.group(bossGroup, workerGroup);
            mqttBootstrap.channel(NioServerSocketChannel.class);

            mqttBootstrap.option(ChannelOption.SO_REUSEADDR, true)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.SO_RCVBUF, 10485760);

            mqttBootstrap.childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            mqttBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    // 设置读写空闲超时时间
                    channelPipeline.addLast(new IdleStateHandler(600, 600, 1200));
                    channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
                    channelPipeline.addLast("decoder", new MqttDecoder());
                    channelPipeline.addLast(new BootNettyMqttChannelInboundHandler());
                }
            });
            ChannelFuture future = mqttBootstrap.bind(address.getPort()).sync();
            if(future.isSuccess()){
                log.info("MqttServer启动成功, 开始监听端口:{}", address.getPort());
                future.channel().closeFuture().sync();
            } else {
                log.error("MqttServer启动失败", future.cause());
            }

            //关闭channel和块，直到它被关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("MqttServer.start error", e);
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
