package com.njzscloud.common.localizer.jt808.support;

import com.njzscloud.common.core.ex.Exceptions;
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 lombok.extern.slf4j.Slf4j;

@Slf4j
public class TcpServer {
    private final int port;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServerBootstrap bootstrap;

    public TcpServer(int port, int bossThreads, int workerThreads) {
        if (port <= 0 || bossThreads <= 0 || workerThreads <= 0) {
            throw Exceptions.error("port、bossThreads和workerThreads必须大于0");
        }
        this.port = port;
        buildServer(bossThreads, workerThreads);
    }


    public void buildServer(int bossThreads, int workerThreads) {
        try {
            // 创建两个EventLoopGroup，bossGroup用于接收客户端连接，workerGroup用于处理连接后的IO操作
            bossGroup = new NioEventLoopGroup(bossThreads);
            workerGroup = new NioEventLoopGroup(workerThreads);
            // 服务器启动辅助类
            bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    // 指定使用NIO的服务器通道
                    .channel(NioServerSocketChannel.class)
                    // 设置服务器通道的选项
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置客户端通道的选项
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 设置通道初始化器，用于配置新接入的通道
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // 添加JT808协议处理器链
                            ch.pipeline()
                                    .addLast(new JT808Decoder())       // 解码器
                                    .addLast(new JT808Encoder())       // 编码器
                                    .addLast(new JT808MessageHandler()); // 消息处理器
                        }
                    });
        } catch (Exception e) {
            log.error("JT808 服务器启动失败", e);
            this.stop();
            throw Exceptions.error(e, "JT808 服务器构建失败");
        }
    }

    public void start() {
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("JT808 服务器已启动，监听端口: {}", port);
            future.channel().closeFuture().addListener(it -> stop());
        } catch (Exception e) {
            log.error("JT808 服务器启动失败，端口: {}", port, e);
            stop();
            throw Exceptions.error(e, "JT808 服务器启动失败");
        }
    }

    public void stop() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
            bossGroup = null;
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
            workerGroup = null;
        }
        log.info("JT808服务器已停止");
    }
}
