package com.iamberry.zk;

import java.net.InetAddress;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractApplicationContext;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.iamberry.zk.ZookeeperQueue;

public class StartZK {
	
	private Logger logger = LoggerFactory.getLogger(StartZK.class);

	public StartZK() {
		logger.info("StartZK start, start Zookeeper...");
		try {
		// 上传当前机器的信息
		ZookeeperQueue.hostInfo();
		// 获取应用配置
		AbstractApplicationContext ctx = (AbstractApplicationContext) SpringContextHolder.getApplicationContext();
		ApplicationConfig applicationConfig = ctx.getBean(ApplicationConfig.class);
		// 获取协议配置，可能存在多个，当port配置为-1时
		Map<String, ProtocolConfig> beansOfType = ctx.getBeansOfType(ProtocolConfig.class);
		String ports = "";
		for (Entry<String, ProtocolConfig> string : beansOfType.entrySet()) {
			ports = ports + string.getValue().getPort() + ",";
		}
			ZookeeperQueue.uploadHostInfo(InetAddress.getLocalHost().getHostAddress(), ports, 0, applicationConfig.getName());
			ZookeeperQueue.monitorNowNodeData(1, ctx);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("StartZK error : " + e.getMessage());
		}
		logger.info("StartZK start, end.");
	}
}
