package com.persagy.socket;

import java.net.InetSocketAddress;

import com.persagy.cameractl.conf.AllStaticConfig;

import ch.qos.logback.core.encoder.ByteArrayUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @version 1.0.0
 * @company persagy
 * @author zhangqiankun
 * @date 2021年10月12日 上午10:06:34
 */
@Slf4j
public class IotSocketClient {

	public static final EventLoopGroup GROUP = new NioEventLoopGroup(1);

	public static final Bootstrap BS = new Bootstrap();
	
	public static Channel channel = null;

	static {
		// 注册线程池、使用NioSocketChannel来作为连接用的channel类
		BS.group(GROUP).channel(NioSocketChannel.class);
	}
	
	/**
	 * 连接
	 * 
	 * @date 2022年8月17日 下午12:00:49
	 */
	public static void connect() {
		try {
			BS.remoteAddress(new InetSocketAddress(AllStaticConfig.toupIp, AllStaticConfig.toupPort)) // 绑定连接端口和host信息
				.handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						log.info("正在连接中...");
						ch.pipeline().addLast(new IotClientHandler());
					}
				});

			ChannelFuture cf = BS.connect().sync(); // 异步连接服务器
			channel = cf.channel();
			log.info("服务端连接成功...");
		} catch (Exception e) {
			log.error("与服务端建立连接失败", e);
		} finally {
			
		}
	}
	
	/**
	 * 断线重连
	 * 
	 * @date 2022年8月16日 下午6:28:24
	 */
    public static void reConnect() {
        // 加入断线后自动重连监听器
        channel = BS.connect(AllStaticConfig.toupIp, AllStaticConfig.toupPort).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.cause() != null) {
                    log.info("Failed to connect: {}", future.cause());
                }
            }
        }).channel();
    }
    
    /**
     * 消息发送
     * @param message
     * @throws Exception
     * @date 2022年8月16日 下午6:28:18
     */
    public static void sendMessage(String message) throws Exception {
        if (channel.isActive() && channel.isWritable()) {
        	log.info("发送数据至服务端: [{}]", message);
        	
        	try {
        		ByteBuf bufff = Unpooled.buffer();
        		bufff.writeBytes(ByteArrayUtil.hexStringToByteArray(message));
                channel.writeAndFlush(bufff);
            } catch (Exception e) {
                log.error("发送数据异常", e);
                channel.close();
            }
		}
    }

	public static void main(String[] args) throws Exception {
		// 192.168.100.102 30054 (5001120003;1;report;20220717100000;17107;ZD1060;1;902;152)
		IotSocketClient.connect();
		IotSocketClient.sendMessage("(5001120003;1;report;20220717100000;17107;ZD1060;1;902;152)");
	}
	
}
