package com.uas.sso.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;

import javax.servlet.ServletContext;

import com.uas.sso.SSOConfig;
import com.uas.sso.exception.SSOException;

/**
 * <p>
 * SSO 配置
 * </p>
 * 
 */
public class SSOConfigurer extends SSOConfig {

	/**
	 * Parameter specifying the location of the sso config file
	 */
	protected static final Logger logger = Logger.getLogger(SSOConfigurer.class.getName());
	private static final String CONFIG_LOCATION_PARAM = "SSOConfigLocation";
	private String configPath = "sso.properties";

	public SSOConfigurer() {
		/* 支持无参构造函数 */
	}

	public SSOConfigurer(String configPath) {
		this.configPath = configPath;
	}

	/**
	 * 
	 * web.xml 启动监听, 初始化
	 * 
	 * @param servletContext
	 * 
	 */
	public void init(ServletContext servletContext) {
		String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
		if (location != null) {
			if (location.indexOf("classpath") >= 0) {
				String[] cfg = location.split(":");
				if (cfg.length == 2) {
					this.initProperties(getInputStream(cfg[1]));
				}
			} else {
				File file = new File(location);
				if (file.isFile()) {
					try {
						this.initProperties(getInputStream(new FileInputStream(file)));
					} catch (FileNotFoundException e) {
						throw new SSOException(location, e);
					}
				} else {
					throw new SSOException(location);
				}
			}
		} else {
			servletContext.log("Initializing is not available SSOConfigLocation on the classpath");
		}
	}

	/**
	 * 
	 * Spring bean 注入初始化
	 * <p>
	 * xml 配置方法：
	 * 
	 * <bean id="ssoConfig" class="com.uas.sso.web.SSOConfigurer"
	 * init-method="init"> <property name="configPath" value="sso.properties" />
	 * </bean>
	 * </p>
	 * 
	 */
	public void init() {
		Properties prop = null;

		/* 尝试文件读取 */
		File file = new File(this.getConfigPath());
		if (file.isFile()) {
			try {
				prop = getInputStream(new FileInputStream(file));
			} catch (FileNotFoundException e) {
				throw new SSOException(this.getConfigPath(), e);
			}
		} else {
			prop = getInputStream(this.getConfigPath());
		}

		/**
		 * 初始化
		 */
		if (prop != null) {
			this.initProperties(prop);
		} else {
			logger.severe("Initializing is not available SSOConfigLocation on the classpath");
		}
	}

	public void shutdown() {
		logger.info("Uninstalling SSO ");
	}

	private Properties getInputStream(String cfg) {
		return getInputStream(SSOConfigurer.class.getClassLoader().getResourceAsStream(cfg));
	}

	private Properties getInputStream(InputStream in) {
		Properties p = null;
		try {
			p = new Properties();
			p.load(in);
		} catch (Exception e) {
			logger.severe(" sso read config file error. \n" + e.toString());
		}
		return p;
	}

	public String getConfigPath() {
		return configPath;
	}

	public void setConfigPath(String configPath) {
		this.configPath = configPath;
	}

}
