package com.czg.mqtt;

import com.czg.mqtt.config.MqttServerProperties;
import com.czg.mqtt.handler.MqttServerHandler;
import com.czg.mqtt.manager.DeviceStatusManager;
import com.czg.mqtt.manager.MqttSubscriptionManager;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
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.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * Netty 服务
 *
 * @author yjjie
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MqttNettyServer implements CommandLineRunner {
    private final MqttServerProperties properties;
    private final MqttSubscriptionManager subscriptionManager;
    private final DeviceStatusManager deviceStatusManager;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ChannelFuture channelFuture;

    @Override
    public void run(String... args) {
        // 在单独的线程中启动 Netty 服务器
        Thread nettyThread = new Thread(this::startServer, "netty-server");
        // 设置为非守护线程，确保应用关闭时服务器也能正常关闭
        nettyThread.setDaemon(false);
        nettyThread.start();
    }

    private void startServer() {
        bossGroup = new NioEventLoopGroup(properties.getBossGroupThreads());
        workerGroup = new NioEventLoopGroup(properties.getWorkerGroupThreads());

        try {
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline()
                                    .addLast("mqttDecoder", new MqttDecoder())
                                    .addLast("mqttEncoder", MqttEncoder.INSTANCE)
                                    .addLast("mqttServerHandler", new MqttServerHandler(subscriptionManager, deviceStatusManager));
                        }
                    });

            channelFuture = bootstrap.bind(properties.getPort()).sync();
            log.info("MQTT服务启动成功，端口：{}", properties.getPort());

            // 添加关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(this::stop));

            // 阻塞等待服务器关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("MQTT服务被中断", e);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            log.error("MQTT服务启动失败", e);
        } finally {
            stop();
        }
    }

    @PreDestroy
    public void stop() {
        log.info("MQTT服务开始关闭...");

        // 先关闭服务器通道
        if (channelFuture != null && channelFuture.channel() != null) {
            try {
                channelFuture.channel().close().sync();
            } catch (InterruptedException e) {
                log.warn("关闭服务器通道时被中断", e);
                Thread.currentThread().interrupt();
            }
        }

        // 再关闭事件循环组
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        log.info("MQTT服务关闭完成");
    }
}
