package ink.wgink.module.instantmessage.websocket.server;

import ink.wgink.module.instantmessage.service.IMessageService;
import ink.wgink.module.instantmessage.service.IWebSocketTextCustomService;
import ink.wgink.module.instantmessage.websocket.channel.WebSocketChannelInitializer;
import ink.wgink.properties.websocket.WebSocketProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: WebSocketServer
 * @Description: WebSocket服务
 * @Author: wanggeng
 * @Date: 2021/9/11 11:00 上午
 * @Version: 1.0
 */
@Component
public class WebSocketServer implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(WebSocketServer.class);
    @Autowired
    private WebSocketProperties webSocketProperties;
    @Autowired
    private IMessageService messageService;
    @Autowired(required = false)
    private IWebSocketTextCustomService webSocketTextCustomService;

    @Override
    public void run() {
        // 通道初始化
        WebSocketChannelInitializer webSocketChannelInitializer = new WebSocketChannelInitializer();
        webSocketChannelInitializer.setWebSocketProperties(webSocketProperties);
        webSocketChannelInitializer.setWebSocketTextCustomHandler(webSocketTextCustomService);
        webSocketChannelInitializer.setMessageService(messageService);

        // server
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            serverBootstrap.group(bossGroup, childGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(webSocketChannelInitializer);
            ChannelFuture channelFuture = serverBootstrap.bind(webSocketProperties.getPort()).sync().addListener(listener -> {
                if (listener.isSuccess()) {
                    StringBuilder socketOutSB = new StringBuilder();
                    socketOutSB.append("******************************\n");
                    socketOutSB.append("**                          **\n");
                    socketOutSB.append("**     WebSocket Server     **\n");
                    socketOutSB.append("**    Start Successfully!   **\n");
                    socketOutSB.append("**                          **\n");
                    socketOutSB.append("**        Port: " + webSocketProperties.getPort() + "        **\n");
                    socketOutSB.append("**                          **\n");
                    socketOutSB.append("******************************\n");
                    System.out.println(socketOutSB);
                }
            });
            // 监听通道关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            LOG.error(e.getMessage(), e);
        } finally {
            bossGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }
}
