/**
 * 
 */


package gov.va.med.cds.tools.cleanup.errorq;


import javax.jms.JMSException;
import javax.jms.Message;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jms.core.MessagePostProcessor;


/**
 * @author sbrush
 *
 */
public class ErrorQListener extends AbstractErrorQListener
{
    private static Log logger = LogFactory.getLog( ErrorQListener.class );
    private int timesProcessed = -1;
   

    /**
     * Used in case of application exceptions and thus avoiding the reprocessing of the failed message
     * by setting a flag that the message is already processed along with failure reason.
     * @param message
     * @param reason
     */
    void sendWithConversionToPreventReprocessing( Message message, final String reason, ErrorQueueCleanUpLogger errorQueueCleanUpLogger)
    {
    	//jmsTemplate.setExplicitQosEnabled(true);
    	
    	final String sendingApp = ErrorQueueThreadLocal.get();
    	jmsTemplate.setPriority(getJmsMessagePriority());
    	jmsTemplate.convertAndSend( message, new MessagePostProcessor()
        {
            
        	public Message postProcessMessage( Message message )
                throws JMSException
            {
                message.clearProperties();
                message.setBooleanProperty( "CDSProcessedMsg", true );
                message.setStringProperty( "CDSFailureReason", reason );
                message.setIntProperty( "CDSNumTimesProcessed", timesProcessed );  // this tag is used for reprocessing all messages
                message.setStringProperty( TEMPLATE_ID, templateId );
                message.setStringProperty( REQUEST_ID, requestId );
                message.setStringProperty(ErrorQueueConstant.SENDING_APP, sendingApp);
 //               message.setJMSPriority( 0 );
                return message;
            }
        } );
        
        errorQueueCleanUpLogger.logRequeued( false );
    }

    public void setTimesProcessed( int timesProcessed )
    {
        this.timesProcessed = timesProcessed;
    }

}
