package com.yonge.toolset.thirdparty.eseal;

import java.util.HashMap;
import java.util.Map;

import com.yonge.toolset.base.exception.ThirdpartyException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.yonge.toolset.thirdparty.eseal.provider.TsignPlugin;

@Component
public class ESealPluginContext implements ApplicationContextAware, InitializingBean {
	
	@Value("${thirdparty.eSealPluginName:Tsign}")
	private String eSealPluginName;
	
	private ApplicationContext applicationContext;

	private final Map<String, String> mapper = new HashMap<String, String>() {
		/**
		 * 
		 */
		private static final long serialVersionUID = -9071481806931421021L;

		{
			put(TsignPlugin.getName(), StringUtils.uncapitalize(TsignPlugin.class.getSimpleName()));
		}
	};

	private ESealPlugin eSealPlugin;

	@Override
	public void afterPropertiesSet() throws Exception {
		if (StringUtils.isBlank(eSealPluginName)) {
			throw new ThirdpartyException("存储插件变量thirdparty.eSealPluginName不能为空");
		}

		eSealPlugin = getStoragePlugin(eSealPluginName);

		if (eSealPlugin == null) {
			throw new ThirdpartyException("电子签章插件{}不存在", eSealPluginName);
		}
	}

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

	private ESealPlugin getStoragePlugin(String vendors) {
		String beanId = mapper.get(vendors);

		if (StringUtils.isBlank(beanId)) {
			throw new ThirdpartyException("电子签章提供商不存在");
		}

		return applicationContext.getBean(beanId, ESealPlugin.class);
	}
}
