/*
 * Created on May 10, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package gov.va.med.esr.common.persistent.comms.hibernate;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

import gov.va.med.fw.model.EntityKey;
import gov.va.med.fw.persistent.DAOException;
import gov.va.med.fw.persistent.DAOOperations;
import gov.va.med.fw.persistent.hibernate.AbstractDAOImpl;
import gov.va.med.esr.common.model.comms.DocumentAccessLog;
import gov.va.med.esr.common.model.comms.HandBookMailQueue;
import gov.va.med.esr.common.model.comms.HealthBenefitPlan;
import gov.va.med.esr.common.persistent.comms.HandBookMailQueueDAO;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 * @author DNS   THOMAS
 * 
 * 
 */
public class HandbookMailQueueDAOImpl extends AbstractDAOImpl implements HandBookMailQueueDAO  {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2329390610776072947L;
	/**
	 * 
	 */
	private static final String FIND_HANDBOOK_BY_PERSON_ID = "handbookQuery_FindByPersonId";
	private static final String FIND_HANDBOOK_STATUS_BY_PERSON_ID = "handbookStatusQuery_FindByPersonId";
	private static final String FIND_ANY_HANDBOOK_SENT_MAILED_BY_PERSON_ID = "handbookSentOrMailedQuery_FindByPersonId_AnyRelease";
	private static final String HANDBOOK_STATUS_RETURN_POST_BY_PERSON_ID = "handbookStatusReturnPostQuery_FindByPersonId";
    private static final String FIND_RAW_PROFILE_DATA_BY_PERSON_ID = "healthBenefitsProfileRawDataQuery";
    private static final String FIND_HANDBOOK_TEMPLATE = "commsTemplateQuery_FindHandbook";
    private static final String FIND_HANDBOOK_BY_PERSON_ID_TEMPLATE_ID_STATUSTYPE_ID = "handbookQuery_FindByPersonIdByTemplateID_STATUS_TYPEID";
    private static final String FIND_HANDBOOK_BY_BATCH_BY_STATUS = "HandBookMailQueue_FindCount_By_Batch_Status";
    private static final String FIND_DELIVERYPREFERENCE_EDITABLE_STATUS = "deliveryPreferenceEditableFieldQuery_FindByPersonId";
    
	private static final String[] personIdParamFields = {"personId"}; 
    private static final String[] rawDataParamFields = {"personVpid"};
    private static final String	 FIND_BY_FILE_ID ="documentAccessLog_FindByFileId";
    private static final String  PARAM_FILEID = "fileId";
	
	private DAOOperations dao = null;

	public DAOOperations getDao() {
		return dao;
	}

	public void  setDao(DAOOperations dao) {
		this.dao = dao;
	}
	
    
    public List findHandbookListByPersonId(String personId) throws DAOException
    {
    	
        BigDecimal[] personIdParamValues = new BigDecimal[]{new BigDecimal(personId)};
        try
        {
           return super.getHibernateTemplate().findByNamedQueryAndNamedParam(FIND_HANDBOOK_BY_PERSON_ID,
                personIdParamFields, personIdParamValues);
        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to find Handbook Mail Queue Entries based on person Id: " + personId, ex);
        }
   }
  
    public List findAnyHandbookSentOrMailedForPersonId(String personId) throws DAOException
    {
    	
        BigDecimal[] personIdParamValues = new BigDecimal[]{new BigDecimal(personId)};
        try
        {
           return super.getHibernateTemplate().findByNamedQueryAndNamedParam(FIND_ANY_HANDBOOK_SENT_MAILED_BY_PERSON_ID,
                personIdParamFields, personIdParamValues);
        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to find Handbook Mail Queue Entries based on person Id: " + personId, ex);
        }
   }
    
    public List findDeliveryPreferenceEditableStatusByPersonId(String personId) throws DAOException
    {
    	
        BigDecimal[] personIdParamValues = new BigDecimal[]{new BigDecimal(personId)};
        try
        {
           return super.getHibernateTemplate().findByNamedQueryAndNamedParam(FIND_DELIVERYPREFERENCE_EDITABLE_STATUS,
                personIdParamFields, personIdParamValues);
        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to find Handbook Mail Queue Entries based on person Id: " + personId, ex);
        }
   }
    public List findHandbookSendStatusListByPersonId(BigDecimal personId,BigDecimal handBookRelaseCtl) throws DAOException
    {
        BigDecimal[] paramValues = new BigDecimal[]{personId,handBookRelaseCtl};
        String[] paramFields = { "personId","handBookReleaseControl"};
		 try
        {
            return super.getHibernateTemplate().findByNamedQueryAndNamedParam(FIND_HANDBOOK_STATUS_BY_PERSON_ID,
            		paramFields, paramValues);
        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to find Handbook Mail Queue Entries in Send Status based on person Id: " + personId, ex);
        }
    }
    public List lastHandbookReturnPostOffice(String personId) throws DAOException
    {
        BigDecimal[] personIdParamValues = new BigDecimal[]{new BigDecimal(personId)};
        try
        {
            return super.getHibernateTemplate().findByNamedQueryAndNamedParam(HANDBOOK_STATUS_RETURN_POST_BY_PERSON_ID,
                personIdParamFields, personIdParamValues);
        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to find Handbook Queue Entries in Return to Post Office Status based on person Id: " + personId, ex);
        }
    }
    public void update(HandBookMailQueue handBookMailQueue) throws DAOException
    {
        super.getHibernateTemplate().update(handBookMailQueue);
    }

    public void merge(HandBookMailQueue handBookMailQueue) throws DAOException
    {
        super.getHibernateTemplate().merge(handBookMailQueue);
    }
    
    /**
     * Inserts a new HandBookMailQueue into the database.  
     * @param handBookMailQueue The comms handBookMailQueue entry to insert.
     * @throws DAOException if any database problems were encountered.
     */
    public void insert(HandBookMailQueue handBookMailQueue) throws DAOException
    {
         // Persist the entry
        saveObject(handBookMailQueue);
    }

    
    // 3.6 CCR 10956
    public List getRawProfileData(String vpid, int receipt_id) throws DAOException {
        // Build the parameter values
        String[] rawDataParamValues = new String[]{vpid};
        try
        {
            // Get the results
            List results = super.getHibernateTemplate().findByNamedQueryAndNamedParam(FIND_RAW_PROFILE_DATA_BY_PERSON_ID,
            		rawDataParamFields, rawDataParamValues);
           
            // Return the results if any results are present.
            if (results != null && results.size() > 0)
            {
            	// filter out any data where the document_receipt.receipt_string does not match our value
            	Iterator iter = results.iterator();
            	while (iter.hasNext()) {
            		HealthBenefitPlan hbp = (HealthBenefitPlan) iter.next();
            		try {
            			int hbp_receipt_id = Integer.valueOf(hbp.getDocumentReceipt().getReceiptString());
            			if (hbp_receipt_id != receipt_id) {
            				iter.remove();
            			}
            		} catch (Exception ex) {
            			//ignore
            		}
            	}
                return results;
            }

        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to find raw profile data: ", ex);
        }

        // Return null if no results were returned.
        return null;
    }
    
    
    public List findHandbookTemplate() throws DAOException
    {
        try
        {
            return super.getHibernateTemplate().findByNamedQuery(FIND_HANDBOOK_TEMPLATE);
        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to find Handbook Template", ex);
        }
    }

    public void recordDocumentAccess(DocumentAccessLog documentAccessLog) throws DAOException
    {
        try
        {
        	insertObject(documentAccessLog);
        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to insert DocumentAccessLog entry", ex);
        }
    }
    //Added for CCR 12155
    public List findDocumentAccessLog(BigDecimal fileId) throws DAOException
    {
        try
        {
        	HibernateTemplate tpl = this.getHibernateTemplate();
			List results = tpl.findByNamedQueryAndNamedParam( FIND_BY_FILE_ID,PARAM_FILEID, fileId);
			return results;
        }
        catch (Exception ex)
        {
            throw new DAOException("Failed to get DocumentAccessLog entry", ex);
        }
       
    }
   

	public HandBookMailQueue findHandBookByIdentifier(BigDecimal identifier) throws DAOException {
		try {
			HibernateTemplate tpl = this.getHibernateTemplate();
			List results = tpl.findByNamedQueryAndNamedParam( FIND_BY_ID,PARAM_IDENTIFIER, identifier);
			
			if ( results != null && results.size() > 0 ) {
			// Should only return one value
				return (HandBookMailQueue)results.get(0);
			} 
			return null;
		} 
		catch (Exception e) {
			throw new DAOException("DAOException - findHandBookByIdentifier UID="+String.valueOf(identifier)+" : ", e);			
		}
		
	} 
	public List findHandBookEntryByPersonByTempOnSendStatus(BigDecimal personId,BigDecimal templId, BigDecimal statusTypeId,BigDecimal handBookRelaseCtl)throws DAOException {
		 try
	        {
			 String[] personIdParamFields = { "personId","templId","statusTypeId","handBookReleaseControl"};
			 BigDecimal[] personIdParamValues = {personId, templId, statusTypeId,handBookRelaseCtl} ;
			 
	           return super.getHibernateTemplate().findByNamedQueryAndNamedParam(FIND_HANDBOOK_BY_PERSON_ID_TEMPLATE_ID_STATUSTYPE_ID,
	                personIdParamFields, personIdParamValues);
	        }
	        catch (Exception ex)
	        {
	            throw new DAOException("Failed to find Handbook Mail Queue Entries based on person Id: " + personId, ex);
	        }
	}
	  public List getHandBookMailQueueCountByBatchIdByStatus(BigDecimal batchRequestId, BigDecimal StatusTypeId) throws DAOException {
	        try {     
	        	
	        	String[] personIdParamFields = { "batchRequestId","statusTypeId"};
				 BigDecimal[] personIdParamValues = {batchRequestId, StatusTypeId} ;
				 
		           return super.getHibernateTemplate().findByNamedQueryAndNamedParam(FIND_HANDBOOK_BY_BATCH_BY_STATUS,
		                personIdParamFields, personIdParamValues);
		    

	        } catch (DataAccessException e) {
	            throw new DAOException("Failed to request list by name", e);
	        }
	      
	    }
	
}
