

package gov.va.med.cds.persistence;


import gov.va.med.cds.filter.EntryFilterInterface;
import gov.va.med.cds.template.generated.JaxBMarshallerUnmarshallerInterface;

import org.hibernate.Session;

import java.util.List;
import java.util.Map;

/***
 * HibernateFilterAwareQueryStrategy is created exclusively to handle domains that implement Hibernate filters
 * @author vhaislbhagav
 *
 */
public class HibernateFilterAwareQueryStrategy
    extends
        DefaultAssociationBasedQueryStrategy
{

    public Map<String, List<String>> domainFilterMappedToHibernateFilter;


    public void setDomainFilterMappedToHibernateFilter( Map<String, List<String>> domainFilterMappedToHibernateFilter )
    {
        this.domainFilterMappedToHibernateFilter = domainFilterMappedToHibernateFilter;
    }


    protected QueryWorkInterface createQueryWork( Session session, QueryAssociationInterface queryAssociation, EntryFilterInterface entryFilter, List<String> personIdentifiers,
                    Class<?> pointInTimeUserType, String siteId, JaxBMarshallerUnmarshallerInterface marshallerUnmarshaller )
    {
        QueryWorkInterface timestampQueryWork = super.createQueryWork( session, queryAssociation, entryFilter, personIdentifiers, pointInTimeUserType, siteId, null );

        for ( String domainName : domainFilterMappedToHibernateFilter.keySet() )
        {
            if ( domainName.equals( entryFilter.getTemplateId() ) )
            {
                for ( String hibernateFilterName : domainFilterMappedToHibernateFilter.get( domainName ) )
                {
                    String tempFilterParamName = hibernateFilterName + "Param";

                    if ( entryFilter.getAdditionalParametersMap() != null )
                    {
                        String tempHibernateFilterParam = ( String )entryFilter.getAdditionalParametersMap().getParameterValue( tempFilterParamName.replace( "FilterParam", "" ) ).getValue();

                        if ( tempHibernateFilterParam != null )
                        {
                            session.enableFilter( hibernateFilterName ).setParameter( tempFilterParamName, tempHibernateFilterParam );
                        }
                    }
                }
            }
        }

        return timestampQueryWork;
    }

}
