package eu.dnetlib.enabling.aas.utils;

import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.StringUtils;

public class SpringUtils {

	protected static final Logger log = Logger.getLogger(SpringUtils.class);
	
	public static final String DEFAULT_TEST_RESOURCE="classpath:/eu/dnetlib/enabling/aas/test-spring-bundle.xml";
	public static final String DEFAULT_INTEGRATION_RESOURCE="classpath:/eu/dnetlib/enabling/aas/integration-spring-bundle.xml";

	public static final String BEAN_REMOTE_IS_REGISTRY = "RemoteISRegistry";
	public static final String BEAN_REMOTE_IS_LOOKUP = "RemoteISLookUp";
	public static final String BEAN_REMOTE_RESULTSET = "RemoteResultSet";
	
	public static ApplicationContext getSpringContext(String resource){
		return getSpringContext(resource, null);
	}
	
	public static ApplicationContext getSpringContext(String resource, ApplicationContext pctx){
		GenericApplicationContext ctx=new GenericApplicationContext(pctx);
		XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
		String base=StringUtils.applyRelativePath(resource, "");
		PropertyPlaceholderConfigurer ppc=new PropertyPlaceholderConfigurer();
		Properties props=new Properties();
		props.setProperty("base.path", base);
		ppc.setProperties(props);
		ppc.setPlaceholderPrefix("#{");
		log.info("base:"+base);
		ctx.addBeanFactoryPostProcessor(ppc);
		if(resource.startsWith("classpath:/")){
			log.info("Loading classpath resource:"+resource);
			xmlReader.loadBeanDefinitions(new ClassPathResource(resource.substring("classpath:/".length())));
		} else if (resource.startsWith("http://") || resource.startsWith("https://")){
			log.info("Loading url resource:"+resource);
			try {
				xmlReader.loadBeanDefinitions(new UrlResource(resource));
			} catch (Exception e) {
				log.error("Cannot load spring context from resource "+resource,e);
				return null;
			}
		} else {
			log.info("Loading file system resource:"+resource);
			xmlReader.loadBeanDefinitions(new FileSystemResource(resource));
		}
		ctx.refresh();
		return ctx;
	}
}
