

package gov.va.med.cds.persistence.hibernate;


import java.util.Map;

import gov.va.med.cds.clinicaldata.DomainEntryPoint;
import gov.va.med.cds.exception.ErrorCodeEnum;
import gov.va.med.cds.persistence.AbstractPersistenceManager;
import gov.va.med.cds.persistence.PersistenceException;
import gov.va.med.cds.template.generated.JaxBMarshallerUnmarshallerInterface;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;
import org.hibernate.SessionFactory;


public abstract class AbstractHibernatePersistenceManager
    extends
        AbstractPersistenceManager
{

    protected static final Log LOGGER = LogFactory.getLog( AbstractHibernatePersistenceManager.class );
    
    private Map<String, SessionFactory> sessionFactoryMap;
    
    protected JaxBMarshallerUnmarshallerInterface marshallerUnmarshaller;


    /**
     * Sets the session factory map with maps template identifiers to session factory instances.
     * 
     * @param sessionFactoryMap session factory passed in from spring injection.
    */
    final public void setSessionFactoryMap( Map<String, SessionFactory> sessionFactoryMap )
    {
        this.sessionFactoryMap = sessionFactoryMap;
    }
    
    
    final SessionFactory getSessionFactory( String templateId )
    {
        SessionFactory sessionFactory = this.sessionFactoryMap.get( templateId );
        if( sessionFactory == null )
        {
            throw new IllegalArgumentException( String.format("No session factory for template identifier '%s' found.", templateId) );
        }
        
        return sessionFactory;
    }
    
    protected Object unmarshalElementToObject(Element data, DomainEntryPoint domainEntryPoint) throws PersistenceException{
    	try{	
    		return this.marshallerUnmarshaller.unmarshal(data, domainEntryPoint.getTemplateUnmarshalClass());
    	}catch(Exception e){
    		
    		throw new PersistenceException(ErrorCodeEnum.UNMARSHALL_ELEMENT, e, domainEntryPoint.getName());
    	}
    	
    }
    
    public void setMarshallerUnmarshaller(
			JaxBMarshallerUnmarshallerInterface marshallerUnmarshaller) {
		this.marshallerUnmarshaller = marshallerUnmarshaller;
	}
    
}
