package cn.com.ty.lift.ud.neety.server;

import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import cn.com.ty.lift.ud.neety.server.handler.ImIdleHandler;
import cn.com.ty.lift.ud.neety.server.handler.WebSocketHandler;
import cn.com.ty.lift.ud.utils.RemotingUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatServer {

    // boss线程
    private EventLoopGroup bossGroup = null;
    // worker线程
    private EventLoopGroup workerGroup = null;

    private boolean useEpoll() {
        return RemotingUtil.isLinuxPlatform() && Epoll.isAvailable();
    }

    /**
     * 启动Netty Server
     *
     * @throws InterruptedException
     */
    public void start(Integer port, Integer readerIdleTime) throws InterruptedException {
        try {
            if (useEpoll()) {
                bossGroup = new EpollEventLoopGroup();
                workerGroup = new EpollEventLoopGroup();
            } else {
                bossGroup = new NioEventLoopGroup();
                workerGroup = new NioEventLoopGroup();
            }
            // netty服务,启动引擎
            ServerBootstrap b = new ServerBootstrap();
            // 主从模式
            b.group(bossGroup, workerGroup)
                // 主线程处理类
                .channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
                // 配置信息
                .option(ChannelOption.SO_BACKLOG, 1024)// 针对主线程配置
                // .childOption(ChannelOption.SO_KEEPALIVE,true);//子线程配置
                // 子线程的处理，Handler
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel channel) throws InterruptedException {

                        ChannelPipeline pipeline = channel.pipeline();
                        // 读、取、读取 心跳检测
//                         pipeline.addLast("idle", new ImIdleHandler(2000, 2500, 3000));
                        pipeline.addLast("ping", new IdleStateHandler(readerIdleTime, 0, 0, TimeUnit.SECONDS));
                        // Http消息编码解码
                        pipeline.addLast("http-codec", new HttpServerCodec());
                        // 参数含义是消息合并的数据大小，如此代表聚合的消息内容长度不超过65536kb。
                        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                        // WebSocket通信支持
                        pipeline.addLast("http-chunked", new ChunkedWriteHandler());
                        // http请求的业务逻辑处理 WebSocket服务端Handler
                        pipeline.addLast("handler", new WebSocketHandler());

                    }

                });

            // 等待客户端连接
            ChannelFuture future = b.bind(port).sync();
            log.info("websoket-server start. port:{} ", port);
            future.channel().closeFuture().sync();
            /*b.bind(25001).sync().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("启动成功");
                    } else {
                        future.cause().printStackTrace();
                    }
                }
            });*/
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
        }

    }

    @PreDestroy
    public void destory() throws InterruptedException {
        bossGroup.shutdownGracefully().sync();
        workerGroup.shutdownGracefully().sync();
        log.info("关闭Netty");
    }

    public static void main(String[] args) {
        try {
            new ChatServer().start(8003,5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
