package com.uas.account.web;

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

import javax.servlet.ServletContext;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.uas.account.AccountConfig;
import com.uas.sso.web.SSOConfigurer;

/**
 * 账户中心配置
 * 
 * <pre>
 * 包含sso配置和账户设置
 * </pre>
 * 
 * @author yingp
 *
 */
public class AccountConfigurer extends AccountConfig implements ApplicationContextAware {

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

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

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

	/**
	 * 
	 * web.xml 启动监听, 初始化
	 * 
	 * @param servletContext
	 * 
	 */
	public void init(ServletContext servletContext) {
		setConfigPath(servletContext.getInitParameter(CONFIG_LOCATION_PARAM));
		init();
	}

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

		try {
			File file = getApplicationContext().getResource(getConfigPath()).getFile();
			prop = getInputStream(new FileInputStream(file));
		} catch (Exception e) {
			e.printStackTrace();
		}

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

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

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

	public String getConfigPath() {
		return configPath;
	}

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

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

}
