/*******************************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ******************************************************************************/
 
package gov.va.med.esr.service.impl;

// Java Classes

// Framework Classes
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.service.trigger.TriggerEvent;
import gov.va.med.fw.service.trigger.TriggerableService;
import gov.va.med.fw.util.InvalidConfigurationException;

import gov.va.med.esr.common.model.lookup.ComLetterTemplateType;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.id.PersonEntityKey;
import gov.va.med.esr.service.CommsLetterRequestService;
import gov.va.med.esr.service.DuplicatePrintRequestServiceException;
import gov.va.med.esr.service.HandBookService;
import gov.va.med.esr.service.PersonService;
import gov.va.med.esr.service.trigger.LetterTriggerEvent;
import gov.va.med.esr.service.trigger.LetterTriggerIdentity;

/**
 * This class processes a letter trigger event message by preparing any needed
 * data and calling the appropriate letter service API.
 * 
 * @author Andrew Pach
 * @version 3.0
 */
public class CommsLetterMessageProcessor extends AbstractComponent implements TriggerableService {
	private PersonService personService = null;

	private CommsLetterRequestService commsLetterRequestService = null;
	private HandBookService handBookService=null;

	/**
	 * Process the LetterTriggerEvent.
	 * 
	 * @param triggerEvent
	 *           The trigger event
	 * @throws ServiceException
	 *            If there were any problems encountered.
	 */
	public void trigger(TriggerEvent triggerEvent) throws ServiceException {
		
		if( this.logger.isDebugEnabled() ) {
			this.logger.debug( "Received a trigger event " + triggerEvent );
		}
		
		LetterTriggerEvent letterTriggerEvent = (LetterTriggerEvent) triggerEvent;

		// Get the person based on the person Id in the trigger event
		Person person = getPerson(letterTriggerEvent);

		// Get the letter trigger identity
		LetterTriggerIdentity letterTriggerIdentity = (LetterTriggerIdentity) letterTriggerEvent
				.getTriggerIdentity();

		try {
			// check to see if it is handbook.if handbook call handbookService
			
			if(letterTriggerIdentity.getDataType().getCode().equals(ComLetterTemplateType.FORM_NUMBER_400H.getCode()) ||
					letterTriggerIdentity.getDataType().getCode().equals(ComLetterTemplateType.FORM_NUMBER_400B.getCode())||
							letterTriggerIdentity.getDataType().getCode().equals(ComLetterTemplateType.FORM_NUMBER_400F.getCode())){
			   this.getHandBookService().requestHandBook(person.getEntityKey().getKeyValueAsString(), letterTriggerIdentity) ;     	
			}else{
			// Call the letter request service to send the letter.
			// CodeCR12825 passed the entire LetterTriggerEvent since it holds data	
			commsLetterRequestService.requestLetter(person, letterTriggerIdentity, letterTriggerEvent);
		}
		} catch(DuplicatePrintRequestServiceException e) {
			if(logger.isWarnEnabled())
				logger.warn("Unable to insert a record for a letter print request....this may be because the batch process " +
						"has not run yet to clear the tracking for Person Id[" + letterTriggerEvent.getPersonId().getKeyValueAsString() +
						"] and Form number[" + letterTriggerIdentity.getDataType().getCode() + "]");
		}
	}

	private Person getPerson(LetterTriggerEvent letterTriggerEvent)
			throws ServiceException {
        try {
        	Person person = null;
			if(letterTriggerEvent.getIdentityTraits() != null)
			{
				person = personService.find(letterTriggerEvent.getIdentityTraits());
			}else 
			{
				PersonEntityKey key = letterTriggerEvent.getPersonId();
				if(key != null)
					person = personService.getPerson(key);
			}			
        	
            return person;
        }
        catch (ServiceException e) {
            throw new ServiceException(
                    "Error retrieving a person from the LetterTriggerEvent",
                    e);
        }
	}

	/**
	 * Verify that the required properties are set.
	 */
	public void afterPropertiesSet() {
		if (personService == null) {
			throw new InvalidConfigurationException(
					"personService must be set on " + getClass().getName());
		}
		if (commsLetterRequestService == null) {
			throw new InvalidConfigurationException(
					"commsLetterRequestService must be set on "
							+ getClass().getName());
		}
	}

	public PersonService getPersonService() {
		return personService;
	}

	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}

	public CommsLetterRequestService getCommsLetterRequestService() {
		return commsLetterRequestService;
	}

	public void setCommsLetterRequestService(
			CommsLetterRequestService commsLetterRequestService) {
		this.commsLetterRequestService = commsLetterRequestService;
	}

	public HandBookService getHandBookService() {
		return handBookService;
	}

	public void setHandBookService(HandBookService handBookService) {
		this.handBookService = handBookService;
	}
}
