package gov.va.med.pharmacy.jms.messaging;

import java.util.Date;

import javax.jms.BytesMessage;

import org.springframework.beans.factory.annotation.Autowired;

import gov.va.med.pharmacy.persistence.model.InboundNcpdpMsgEntity;
import gov.va.med.pharmacy.persistence.service.InboundNcpdpMsgService;

public class InboundMsgProcessor {

	private static final org.apache.logging.log4j.Logger LOG = org.apache.logging.log4j.LogManager.getLogger(InboundMsgProcessor.class);
	
	@Autowired
	private InboundNcpdpMsgService inboundNcpdpMsgService;

	public void getERxMessage(BytesMessage eRxMessage) {

		try {
			
			LOG.info("Trying to persist incoming JMS message.");
			
			// persist the message.

			InboundNcpdpMsgEntity inboundeRx = new InboundNcpdpMsgEntity();

			Date date = new Date();

			inboundeRx.setErxStatusByPatientChkStatus("0000");
			inboundeRx.setErxStatusByDrugChkStatus("0000");
			inboundeRx.setErxStatusByProviderChkStatus("0000");

			inboundeRx.setErxStatusByMessageStatus("0000");

			int messageLength = new Long(eRxMessage.getBodyLength()).intValue();

			byte[] messageByteArray = new byte[messageLength];

			eRxMessage.readBytes(messageByteArray, messageLength);

			String message = new String(messageByteArray);

			inboundeRx.setMessage(message);

			inboundeRx.setPharmacyId(0);

			inboundeRx.setCreatedDate(date);

			inboundeRx.setUpdatedDate(date);

			inboundeRx.setReceivedDate(date);

			inboundNcpdpMsgService.saveInboundERx(inboundeRx);

		} catch (Exception e) {
			
			LOG.error("Error in getERxMessage:"+e.getMessage());
		}

	}

	

}
