package com.jpsoft.uniview;

import com.jpsoft.uniview.codec.HttpDecoder;
import com.jpsoft.uniview.codec.HttpEncoder;
import com.jpsoft.uniview.handler.ParseHttpHandler;
import com.jpsoft.uniview.handler.PersonVerificationHandler;
import com.jpsoft.uniview.handler.ResponseDataHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class MainApplication {
    private static final int READ_TIME_OUT = 300;

    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup,workerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer(){
            @Override
            protected void initChannel(Channel channel) throws Exception {
                //通道空闲超时时间
                channel.pipeline().addLast(new IdleStateHandler(READ_TIME_OUT, READ_TIME_OUT, READ_TIME_OUT, TimeUnit.SECONDS));

                channel.pipeline().addLast(new HttpEncoder());
                channel.pipeline().addLast(new HttpDecoder());
                channel.pipeline().addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));

                //保活超时时间
                channel.pipeline().addLast(new ReadTimeoutHandler(READ_TIME_OUT));
                channel.pipeline().addLast(new ParseHttpHandler());
                channel.pipeline().addLast(new PersonVerificationHandler());
                channel.pipeline().addLast(new ResponseDataHandler());
            }
        });

        int port = 7988;

        ChannelFuture channelFuture = b.bind("0.0.0.0",port);
        Channel serverChannel = channelFuture.channel();

        channelFuture.addListener((future)-> {
            if(future.isSuccess()){
                log.warn(String.format("netty 已监听%d端口",port));
            }
        });
    }
}
