package com.willalp.control.netty;

import io.netty.bootstrap.ServerBootstrap;
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.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;


/**
 * @author hs
 */
public final class TcpServer {

    private final static Logger logger = LoggerFactory.getLogger(TcpServer.class);

    private ChannelHandlerAdapter channelHandlerAdapter;

    private volatile EventLoopGroup bossGroup;

    private volatile EventLoopGroup workerGroup;

    private volatile ServerBootstrap bootstrap;

    private volatile boolean closed = false;

    private int localPort;

    public TcpServer(int localPort, ChannelHandlerAdapter channelHandlerAdapter) {
        this.localPort = localPort;
        this.channelHandlerAdapter = channelHandlerAdapter;
    }

    public void close() {
        closed = true;
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        logger.info("Stopped Tcp Server: " + localPort);
    }

    public void init(IAddNettyChannelMap iAddNettyChannelMap) {
        closed = false;
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                iAddNettyChannelMap.execute(ch);
                /*
                 * 使用心跳检测处理器
                 * 读空闲 写空闲 读写空闲 的超时时间
                 * 最后一个参数是 时间的单位
                 * IdleStateHandler发现有空闲的时候 会触发 IdleStateEvent时间
                 * 他会把事件推送给下一个 handler的指定方法 userEventTriggered 去处理
                 * */
                ch.pipeline().addLast(new IdleStateHandler(5, 10, 20, TimeUnit.SECONDS));
                ch.pipeline().addLast(channelHandlerAdapter);
            }
        });
        doBind();
    }

    protected void doBind() {
        if (closed) {
            return;
        }

        ChannelFuture f = bootstrap.bind(localPort).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    logger.info("Started Tcp Server: " + localPort);
                } else {
                    logger.info("Started Tcp Server Failed: " + localPort);
                    f.channel().eventLoop().schedule(() -> doBind(), 1, TimeUnit.SECONDS);
                }
            }
        });
        try {
            f.sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
