package com.szpg.plc.server;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;

import io.netty.bootstrap.Bootstrap;
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;

public class ACUClient {
	
	private final Logger logger = Logger.getLogger(this.getClass().getName());

	private final String host;
	private final int port;
	
	private Channel channel;
	
	private String acucode; // ACU编码
	private String net;  //网络号
	private String node; //节点号
	private String unit; //单元号
	
	public ACUClient(String host, int port) {
		this.host = host;
		this.port = port;
	}
	
	public Channel getChannel() {
		return channel;
	}

	public void setChannel(Channel channel) {
		this.channel = channel;
	}
	
	public String getAcucode() {
		return acucode;
	}

	public void setAcucode(String acucode) {
		this.acucode = acucode;
	}

	public String getNet() {
		return net;
	}

	public void setNet(String net) {
		this.net = net;
	}

	public String getNode() {
		return node;
	}

	public void setNode(String node) {
		this.node = node;
	}

	public String getUnit() {
		return unit;
	}

	public void setUnit(String unit) {
		this.unit = unit;
	}

	@Override
	public String toString() {
		return "ACUClient[code=" + acucode + ", host=" + host + ", port=" + port + "]";
	}
	
	/**
	 * 返回保存在Map中的键值
	 * @return
	 */
	public String getKey() {
		return host + ":" + port;
	}

	public void start() throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();//处理各种请求，如处理链接请求，发送接收数据等
		try {
			Bootstrap boot = new Bootstrap();//配置整个netty，串联起各组件
			boot.group(group);
			boot.channel(NioSocketChannel.class);
			boot.remoteAddress(new InetSocketAddress(host, port));
			//配置handler
			boot.handler(new ChannelInitializer<SocketChannel>() {
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new ACUClientHandler());
				}
			});
			
			//注册监听事件，来判断操作的成功或失败
			ChannelFuture future = boot.connect().sync();
			future.addListener(new ChannelFutureListener() {
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
						// 连接成功
						logger.info(future.channel().remoteAddress() + "连接成功");
					} else {
						logger.error(future.channel().remoteAddress() + "连接失败");
						future.cause().printStackTrace();
					}
				}
			});
			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}
	}
}
