/*
 * 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.List;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;

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.AacLetterRequest;
import gov.va.med.esr.common.persistent.comms.AacLetterRequestDAO;
import gov.va.med.esr.common.persistent.comms.PrintRequestDuplicationException;

/**
 * @author DNS   TSAIG
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class AacLetterRequestDAOImpl extends AbstractDAOImpl implements
		AacLetterRequestDAO {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6392209931355445693L;
    private DAOOperations dao = null;
    
    public DAOOperations getDao() {
        return dao;
    }

    public void  setDao(DAOOperations dao) {
        this.dao = dao;
    }

    
	public AacLetterRequest findAacLetterRequestById(BigDecimal requestId)
			throws DAOException {
		try {
			// org.springframework.orm.hibernate3.HibernateTemplate t =
			// getHibernateTemplate();

			List lst = super.getHibernateTemplate().find(
					"from AacLetterRequest req where req.identifier = ?",
					requestId);

			if (lst != null && lst.size() > 0)
				return (AacLetterRequest) lst.get(0);

		} catch (Exception e) {
			throw new DAOException("Failed to find AAC letter request by id", e);
		}

		return null;
	}

	public List findAacLetterRequestByPartyId(BigDecimal partyId)
			throws DAOException {
		return null;
	}

	public List findAacLetterRequestBetweenRequestIds(BigDecimal startId,
			BigDecimal endId) throws DAOException {
		try {
			// NOTE: It is important to order by form number for easier
			// detecting of duplicate requests for the same Person
			List lst = super
					.getHibernateTemplate()
					.find(
							"from AacLetterRequest req where req.identifier > ? and req.identifier <= ?",
							new BigDecimal[] { startId, endId });

			return lst;

		} catch (Exception e) {
			throw new DAOException("Failed to find AAC letter request by id", e);
		}
	}
    
    //public List find(String query, Object[] params, int firstRecord, int maxRecord, int fetchSize) throws DAOException {
    public List findAacLetterRequestBetweenRequestIdsByBatch(BigDecimal startId,BigDecimal endId, int fetchSize) throws DAOException {
        try {
            // NOTE: It is important to order by form number for easier
            // detecting of duplicate requests for the same Person
            
            String query = "aacExportCommand.findRequestsBeweenIds";
            int firstRecord = 0; //always start from 0
            int maxRecord   = fetchSize;
            
            String[] paramNames = { "prevReqId","curReqId"};
            BigDecimal[] paramValues = {startId, endId} ;
            List lst = dao.find(query, paramNames,paramValues,  firstRecord, maxRecord, fetchSize);

            return lst;

        } catch (Exception e) {
            throw new DAOException("Failed to find AAC letter request by id", e);
        }
    }
    
	public List findCmsLetterRequests() throws DAOException {
        try {
            // NOTE: It is important to order by form number for easier
            // detecting of duplicate requests for the same Person
            String query = "cmsExportCommand.findCmsLetterRequests";
            
            List lst = dao.find(query);

            return lst;

        } catch (Exception e) {
            throw new DAOException("Failed to find AAC letter request by id", e);
        }
	}

	public List findAacLetterRequestsByLogId(BigDecimal logId)
			throws DAOException {
		try {

			List lst = super
					.getHibernateTemplate()
					.find(
							"from AacLetterRequest req where req.commsLogEntry.identifier = ?",
							logId);

			return lst;

		} catch (Exception e) {
			throw new DAOException(
					"Failed to find AAC letter request by log id", e);
		}
	}

	public void insert(AacLetterRequest request)
			throws DAOException {
		try {
			super.insertObject(request);
			// force immediate detection of integrity constraint (rather than through commit flush at proxy layer)
			super.getHibernateTemplate().flush(); 
		} catch(DataIntegrityViolationException e) {
			throw new PrintRequestDuplicationException(
					"No duplication letter allowed (same form for the same person per batch). Failed dupe check on COMMS_PRINT_REQUEST",
					e);			
		} catch (DAOException ex) { 
			if(ex.getCause() instanceof DataIntegrityViolationException)
				throw new PrintRequestDuplicationException(
						"No duplication letter allowed (same form for the same person per batch). Failed dupe check on COMMS_PRINT_REQUEST",
						ex.getCause());
			
			throw ex;
		}
	}

	public void deleteById(AacLetterRequest request) throws DAOException {

		super.removeObject(request.getEntityKey());

	}

    public void mergeObject(AacLetterRequest request)  throws DAOException
    {
        try {
            getHibernateTemplate().merge(request);
        } catch (DataAccessException e) {
            throw new DAOException("Failed to merge request " , e);
        }
    }
    
    
    public AacLetterRequest findAacLetterRequestByUniqueCode(String uniqueCode) throws DAOException {
        try {
            List lst= super.getHibernateTemplate().find(
                    "from AacLetterRequest req where req.commsPrintRequestDupeCheck = ?",
                    uniqueCode);

            if (lst != null && lst.size() > 0)
                return (AacLetterRequest) lst.get(0);

        } catch (Exception e) {
            throw new DAOException("Failed to find AAC letter request by unique code", e);
        }

        return null;
    }    
}
