package com.xxl.job.admin;

import com.xxl.job.admin.util.ZookeeperClientUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.StringUtils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

/**
 * @author xuxueli 2018-10-28 00:38:13
 */
@SpringBootApplication
public class XxlJobAdminApplication {

	public static void main(String[] args){
		init(args);
        SpringApplication.run(XxlJobAdminApplication.class, args);
	}

	private static void init(String[] args){
		// 促使化zookeeper客户端工具类
		if(args == null || args.length == 0){
			throw new RuntimeException("请传入zookeeper的地址");
		}
		ZookeeperClientUtil.init(args[0], "/weixt/conf");
		// 创建zookeeper客户端
		ZookeeperClientUtil configurationClient = new ZookeeperClientUtil();
		try {
			String resource = XxlJobAdminApplication.class.getResource("/application.properties").getPath();
			Properties properties = new Properties();
			properties.load(new FileInputStream(resource));
			makeProperties(properties,configurationClient,"spring.datasource.url");
			makeProperties(properties,configurationClient,"spring.datasource.username");
			makeProperties(properties,configurationClient,"spring.datasource.password");
			FileOutputStream fileOutputStream = new FileOutputStream(resource);
			properties.store(fileOutputStream,"");
			fileOutputStream.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	private static void makeProperties(Properties properties, ZookeeperClientUtil configurationClient, String key){
		String value = configurationClient.getData(configurationClient.mainPath + "/" + key);
		if(StringUtils.isEmpty(value)){
			throw new RuntimeException("zookeeper中没有该属性的值：" + key);
		}
		properties.setProperty(key,value);
	}
}