package server;

import com.sun.org.apache.regexp.internal.RE;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Properties;

/**
 * @author yuli
 * @Description:TODO
 * @ClassName TcpServer
 **/
public class TcpServer {

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

    // 服务器地址端口
//    private static final String IP = "192.168.0.112";
//    private static final String IP = "192.168.0.107";
    private static final int PORT = 9200;

    public static  String deviceId ;

    /** 用于分配处理业务线程的线程组个数 */
    protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors() * 2;
    /** 业务出现线程大小 */
    protected static final int BIZTHREADSIZE = 4;

    /*
     * NioEventLoopGroup实际上就是个线程池,
     * NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件,
     * 每一个NioEventLoop负责处理m个Channel,
     * NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel
     */
    private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);

    //    线程内容
    protected static void run() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
//                Decode是对发送的信息进行编码、
//                @param maxFrameLength  帧的最大长度
//                @param lengthFieldOffset length字段偏移的地址
//                @param lengthFieldLength length字段所占的字节
//                @param lengthAdjustment 修改帧数据长度字段中定义的值，
//                可以为负数 因为有时候我们习惯把头部记入长度,若为负数,则说明要推后多少个字段
//                @param initialBytesToStrip 解析时候跳过多少个长度
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(new StringDecoder());
                pipeline.addLast(new TcpServerHandler());
                TcpServerHandler.openComm();
            }
        });
//        异步绑定端口
        InetAddress addr = InetAddress.getLocalHost();
        logger.info("Local HostAddress:"+addr.getHostAddress());
        String hostname = addr.getHostName();
        byte[] mac = NetworkInterface.getByInetAddress(addr).getHardwareAddress();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            // mac[i] & 0xFF 是为了把byte转化为正整数
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length() == 1 ? 0 + s : s);
        }
        deviceId = sb.toString();
        logger.info("mac: "+sb.toString());
        logger.info("Local host name: "+hostname);
        b.bind(addr.getHostAddress(), PORT).sync();
//        b.bind(IP, PORT).sync();
        logger.info("TCP Server Started");

    }
//            关闭端口
    protected static void shutdown() {
        TcpServerHandler.closeComm();
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    public static void main(String[] args) throws Exception {
        logger.info("Starting TCP Server...");
        Properties config = new Properties();
        InputStream in = ClassLoader.getSystemResourceAsStream( "config.properties");
        config.load(in);
        TcpServerHandler.serverUrl = config.getProperty("serverUrl");
        logger.info("后端接口>>" + TcpServerHandler.serverUrl);
        TcpServer.run();
        // TcpServer.shutdown();
    }
}
