package client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.TcpServer;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author yuli
 * @ClassName TcpClient
 **/
public class TcpClient {

    private static Logger logger = LoggerFactory.getLogger(TcpServer.class);
    public static String HOST;
    public static String PORT;
    public static  String deviceId ;

    static {
        InputStream in = ClassLoader.getSystemResourceAsStream("config.properties");
        Properties config = new Properties();
        try {
            config.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HOST = config.getProperty("gpsServerIP");
        PORT = config.getProperty("gpsServerPort");
        logger.info("gps服务器地址>>" + HOST);
        logger.info("gps服务器端口>>" + PORT);
    }

    public static Bootstrap bootstrap = getBootstrap();
    public static Channel channel = getChannel(HOST, Integer.parseInt(PORT));

    /**
     * 初始化Bootstrap
     */
    public static final Bootstrap getBootstrap() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("encoder", new StringEncoder());
                pipeline.addLast("decoder", new StringDecoder());
                pipeline.addLast("handler", new TcpClientHandler());
                TcpClientHandler.openComm();
            }
        });
        b.option(ChannelOption.SO_KEEPALIVE, true);
        return b;
    }

    //    连接端口
    public static final Channel getChannel(String host, int port) {
        Channel channel = null;
        try {
            channel = bootstrap.connect(host, port).sync().channel();
        } catch (Exception e) {
            System.out.println("Connect Server(IP{},PORT{}) Failed" + "host:" + host + "port:" + port + "e:" + e);
            return null;
        }
        return channel;
    }

    /**
     * 发送信息
     *
     * @param msg
     * @return void
     */
    public static void sendMsg(String msg) throws Exception {
        if (channel != null) {
            channel.writeAndFlush(msg).sync();
        } else {
            System.out.println("Msg Send Failed , Connection Lost!");
        }
    }

    public static final String client = "gpsclient";

    public static void main(String[] args) throws Exception {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            logger.info("Local HostAddress:"+addr.getHostAddress());
            String hostname = addr.getHostName();
            deviceId = hostname;
            logger.info("Local host name: "+hostname);
            Properties config = new Properties();
            InputStream in = ClassLoader.getSystemResourceAsStream("config.properties");
            config.load(in);
            TcpClientHandler.serverUrl = config.getProperty("serverUrl");
            logger.info("服务器后端接口>>" + TcpClientHandler.serverUrl);
            TcpClient.sendMsg(client);

            //创建定时器
            final HashedWheelTimer timer = new HashedWheelTimer(
                    Executors.defaultThreadFactory(), 10, TimeUnit.MILLISECONDS, 2);

            timer.newTimeout(new TimerTask() {
                @Override
                public void run(final Timeout timeout) throws Exception {
                    logger.error("timer:单点信号");

                    TcpClientHandler.positioning();

                    timer.newTimeout(this, 10, TimeUnit.SECONDS);//结束时候再次注册
                }
            }, 5, TimeUnit.MILLISECONDS);

        } catch (Exception e) {
            System.out.println("main err:" + e);
        }
    }


}
