package gov.va.med.esr.jms.vadir;

import gov.va.med.esr.jms.vadir.inboundRequest.VadirServiceMilitaryHistoryRequest;
import gov.va.med.esr.jms.vadir.outboundResponse.VadirServiceResponseType;
import gov.va.med.esr.jms.vadir.outboundResponse.VadirServiceResponseWrapper;

import java.io.Serializable;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import org.apache.log4j.Logger;
/**
 * @author DNS   barryc
 */
@Component
public class VadirErrorMessageJMSListener implements MessageListener {
	private static final Logger logger = Logger
			.getLogger(VadirErrorMessageJMSListener.class);

	// ------------------------------------------- Fields

	@Resource(name = "vadirOutboundJMSTemplate")
	private JmsTemplate jmsTemplate;

	// ------------------------------------------- Business Methods

	@Override
	public void onMessage(Message message) {
		logger.trace("Received JMS message that errored out: {}" + message);

		if (message instanceof ObjectMessage == false) {
			logger.error("Message must be of type {}" +
					ObjectMessage.class.getName());
			return;
		}

		ObjectMessage om = (ObjectMessage) message;

		Serializable o = null;
		try {
			o = om.getObject();
		} catch (JMSException e) {
			logger.error("Unexpected exception while reading JMS message", e);
			return;
		}

		if (o instanceof VadirServiceMilitaryHistoryRequest == false) {
			logger.error("Message must contain a {}, but instead contained a {}" +
					VadirServiceMilitaryHistoryRequest.class.getName()+ o
							.getClass().getName());
			return;
		}

		VadirServiceMilitaryHistoryRequest vsr = (VadirServiceMilitaryHistoryRequest) o;

		String whichServiceNotAvailable = null;
		try {
			whichServiceNotAvailable = om
					.getStringProperty(VadirRequestJMSListener.SERVICE_NOT_AVAILABLE_MESSAGE);
		} catch (JMSException e) {
			logger.error("Couldn't retrieve the "
					+ VadirRequestJMSListener.SERVICE_NOT_AVAILABLE_MESSAGE
					+ " property of the message", e);
			return;
		}

		sendErrorResponse(vsr.getRequestId(), vsr.getPersonId(),
				whichServiceNotAvailable);
	}

	private void sendErrorResponse(long requestId, long personId, String error) {
		final VadirServiceResponseWrapper r = new VadirServiceResponseWrapper(
				requestId, personId, VadirServiceResponseType.REQUEST_ERROR,
				error);
		logger.debug("Sending response {}" + r);
		jmsTemplate.send(new VadirRequestJMSListener.VadirMessageCreator(r));
	}

}
