package com.iamberry.zk;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;
/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年9月13日
 * @explain	zookeeper的实例工厂类
 */
public final class ZookeeperFactory {
	
	/**
	 * 获取实现了slf4j接口的日志
	 */
	private static Logger logger = LoggerFactory.getLogger(ZookeeperFactory.class);

	/**
	 * zk超时时间
	 */
	private static int TIME_OUT = 2000;
	
	/**
	 * zk是否允许,true:允许，false:没有运行
	 */
	private static volatile boolean IS_ZK_RUN = false;
	
	public static boolean isZkRun() {
		return IS_ZK_RUN;
	}

	/**
	 * 全局保存Zookeeper的实例
	 */
	private static ZkClient zkClient = null;
	
	/**
	 * 获取Zk的实例
	 */
	public static ZkClient getZkClient() {
		return zkClient;
	}
	
	/**
	 * 一旦启动项目， 自动链接Zookeeper
	 * Class 装载的顺序，静态代码块优先
	 */
	static {
		/*// 加载
		propertiesPersister = new DefaultPropertiesPersister();
		resourceLoader = new PathMatchingResourcePatternResolver();
		
		// 通过JVM环境参数，指定是否启动zk
		String zkStart = System.getProperty("zk.start");
		logger.info("zk.start property:" + zkStart);
		if ("true".equals(zkStart) || zkStart == null) {
			initZookeeper();
		}*/
	}
	
	/**
	 * 连接zookeeper
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public synchronized static void initZookeeper() {
		System.out.println("加载init");
		if (isZkRun()) {
			return;
		}
		logger.info("初始化Zookeeper连接");
		try {
			zkClient = new ZkClient(getConnectionStr(), TIME_OUT);
			IS_ZK_RUN = true;
		} catch (Exception e) {
			logger.error("初始化Zookeeper异常：" + e.getMessage());
		}
	}
	
	/**
	 * 获取Zookeeper链接
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static String getConnectionStr() throws FileNotFoundException, IOException {
		logger.info("读取zookeeper的配置文件...");
		try {
			Properties props = loadProperties("zk.properties");
			String host = (String) props.get("zookeeper.host");
			String port = (String) props.get("zookeeper.port");
			logger.info("读取配置文件完毕,host:" + host + ",port:" + port);
			return new StringBuilder(host).append(":").append(port).toString();
		} catch (Exception e) {
			return "127.0.0.1:2181"; 
		}
	}
	
	/**
	 * 载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的载入. 文件路径使用Spring Resource格式, 文件编码使用UTF-8.
	 * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
	 */
	public static Properties loadProperties(String... resourcesPaths) throws IOException {
		if (resourcesPaths == null) {
			throw new NullPointerException("No resource path");
		}
		
		Properties props = new Properties();
		for (String location : resourcesPaths) {
			logger.debug("Loading properties file from:" + location);
			InputStream is = null;
			try {
				Resource resource = resourceLoader.getResource(location);
				is = resource.getInputStream();
				propertiesPersister.load(props, new InputStreamReader(is, DEFAULT_ENCODING));
			} catch (IOException ex) {
				logger.info("Could not load properties from classpath:" + location + ": " + ex.getMessage());
			} finally {
				if (is != null) {
					is.close();
				}
			}
		}
		return props;
	}
	// 编码
	private static final String DEFAULT_ENCODING = "UTF-8";
	// Spring-core 获取配置文件的类
	private static PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
	// Spring-core 获取资源的类
	private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver();
}