package it.businesslogic.ireport.connection;

import java.util.StringTokenizer;

import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 
 * 
 * @author Jeffrey Payne
 *
 */

public class JRSpringLoadedHibernateConnection extends JRHibernateConnection {
	
	private final static String PROP_KEY_SPRING_CONFIG = "spring.loaded.hibernate.spring.config";
	private final static String PROP_KEY_SESSION_FACTORY_ID = "spring.loaded.hibernate.session.factory.id";
	
	private String springConfig = null;
	private String sessionFactoryBeanId = null;
	
	public String getDescription(){ return "Spring Loaded Hibernate connection"; }

	
	public ApplicationContext getApplicationContext() {
		
                StringTokenizer parser = new StringTokenizer(getSpringConfig(), ",");
                String[] configs = new String[parser.countTokens()];
                int iCount = 0;
                while (parser.hasMoreTokens()) {
                        configs[iCount++] = parser.nextToken();
                }
                return new ClassPathXmlApplicationContext(configs);
	}

	public String getSessionFactoryBeanId() {
		return sessionFactoryBeanId;
	}


	public void setSessionFactoryBeanId(String sessionFactoryBeanId) {
		this.sessionFactoryBeanId = sessionFactoryBeanId;
	}


	public String getSpringConfig() {
		return springConfig;
	}


	public void setSpringConfig(String springConfig) {
		this.springConfig = springConfig;
	}
	
	 public SessionFactory getSessionFactory() {
		 
		 return (SessionFactory)getApplicationContext().getBean(getSessionFactoryBeanId());
		 
	 }
	 
        /*
         *  This method return all properties used by this connection
         */
        public java.util.HashMap getProperties()
        {    
            java.util.HashMap map = new java.util.HashMap();
            map.put(PROP_KEY_SESSION_FACTORY_ID, getSessionFactoryBeanId());
            map.put(PROP_KEY_SPRING_CONFIG, getSpringConfig());
            return map;
        }

        public void loadProperties(java.util.HashMap map)
        {
            setSessionFactoryBeanId((String)map.get(PROP_KEY_SESSION_FACTORY_ID));
            setSpringConfig((String)map.get(PROP_KEY_SPRING_CONFIG));
        }
	
}