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

// Java classes

// Library classes
import java.util.Set;

import org.apache.commons.lang.Validate;

// Framework classes
import gov.va.med.fw.model.EntityKey;
import gov.va.med.fw.persistent.DAOException;
import gov.va.med.fw.service.ServiceException;

// EDB classes
import gov.va.med.esr.common.clock.Clock;
import gov.va.med.esr.common.model.ee.PurpleHeart;

import gov.va.med.esr.common.model.lookup.RegistryType;
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.EligibilityEnrollmentService;
import gov.va.med.esr.service.PersonService;
import gov.va.med.esr.service.PurpleHeartService;
import gov.va.med.esr.service.RegistryService;

/**
 * Service for updating Purple Heart information.
 * 
 * @author Muddaiah Ranga
 * @version 1.0
 */
public class PurpleHeartServiceImpl extends AbstractHistoricalInfoServiceImpl implements PurpleHeartService {

   /**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = 7820675252292861686L;
	/**
	 * An instance of eligibilityEnrollmentService
	 */
	private EligibilityEnrollmentService eligibilityEnrollmentService = null;
    
	/**
     * An instance of registryService.
     */
    
    private RegistryService registryService = null;

	
	public PurpleHeartServiceImpl() 
	{
	    super();
	}
   
   /**
    * 1. Merge purple heart with the person in file
    * 2. Calculate EE
    * 3. Trigger a message to the site that the veteran has visited
    * 4. Saves the person to the database
    * 
    * @param incoming An incoming person containing purple heart info
    * @return An updated person with purple heart information
    * @throws ServiceException Thrown if failed to update 
    */
   public Person updatePurpleHeart(Person incoming) throws ServiceException 
   {
       return this.updatePurpleHeart(incoming, null);
   }
   
   /**
     * @see gov.va.med.esr.service.PurpleHeartService#updatePurpleHeart(gov.va.med.esr.common.model.person.Person,
     *      gov.va.med.esr.common.clock.Clock.Type)
     */
    public Person updatePurpleHeart(Person incoming, Clock.Type clockType)
            throws ServiceException {
        Validate.notNull( incoming, "A incoming person must not be null");
        
        // This call should always return a person since a person must have
        // already been querried through a search to display insurance info 
        // on a screen
        PersonService personService = this.getPersonService();
        Person result = personService.getPerson( (PersonEntityKey)incoming.getEntityKey() );

        // Ensure that something changed on the incoming entity as compared to the onFile entity.
        // Only do compare if not being executed by a batch job that has passed non-null clockType 
        if (clockType == null) {
            ensureEntityChanged(incoming, result);
        }

       // this.addPurpleHeartRegistryInfo(incoming);
        // Step 1: Update the purple heart information
        result = this.getPurpleHeartRuleService().managePurpleHeart(incoming,result,clockType);
        
        // Step 2: Get an enrollment service to determine eligibility. Letters and e-mail
        // will be triggered in this step
        result = this.getEligibilityEnrollmentService().assessEEImpact(result, false, clockType);
        
        // Step 3: Send update Z11/bulletins
        this.getEventRuleService().handleCommonPostEvents(result, true);
        
	    //Step 4:Link purpleHeart registry.
        PurpleHeart incomingPurpleHeart=incoming.getPurpleHeart();
	    if(incomingPurpleHeart!=null && result!=null && incomingPurpleHeart.getRegistryTrait()==null)
	    {
	    	RegistryType regType=(RegistryType)this.getLookupService().getByCode(RegistryType.class,RegistryType.CODE_PH_REGISTRY.getCode());	    
	    	this.getRegistryService().linkPersonRegistry(incomingPurpleHeart, result.getPurpleHeart(), incoming, result, regType, true);
	    }
        
        // Step 5: Save the updated person
        return personService.save( result );
    }
    /**
     * This method adds PurpleHeart info
     * @param incoming
     */
    public void addPurpleHeartRegistryInfo(Person incoming ) throws ServiceException 
    {
        
//        PurpleHeart purpleHeart = (incoming != null) ? incoming.getPurpleHeart() : null;
//        Registry registry=null;
//        	if(purpleHeart != null)
//	        {
//	            if(purpleHeart.getRegistryTrait() == null) 
//	            {
//	            	RegistrySearchCriteria registrySearchCriteria=getRegistryService(). getRegistrySearchCriteria(incoming,
//	            													RegistryType.CODE_PH_REGISTRY.getCode());            	
//	            	registry=getRegistryService().getMatchingRegistry(registrySearchCriteria);
//	            	if(registry!=null)
//	            	{
//	            		purpleHeart.setRegistryTrait(new RegistryTrait());
//	            		purpleHeart=getMergeRuleService().mergeRegistry((PurpleHeart)registry, purpleHeart);     
//	            	}
//	            	else
//	            	{
//	            		RegistryTrait regTrait=getRegistryService().createRegistryTrait(incoming,RegistryType.CODE_PH_REGISTRY.getCode());
//	            		purpleHeart.setRegistryTrait(regTrait);
//	            	}
//	            	
//	            	incoming.setPurpleHeart(purpleHeart);
//	            }
//	        }            
        }

    /**
     * @see gov.va.med.esr.service.PurpleHeartService#getPurpleHeartHistoryByChangeTime(gov.va.med.esr.service.impl.ChangeEvent)
     */
    public HistoricalInfo getPurpleHeartHistoryByChangeTime(ChangeEvent event)
            throws ServiceException {
        try {
            return this.getHistoryDAO().getHistoryByChangeTime(event);
        } catch (DAOException e) {
            throw new ServiceException(e.getMessage(),e);
        }
    }

    /**
     * @see gov.va.med.esr.service.PurpleHeartService#getPurpleHeartHistoryChangeTimes(gov.va.med.fw.model.EntityKey)
     */
    public Set getPurpleHeartHistoryChangeTimes(EntityKey personID)
            throws ServiceException {
        try {
            return this.getHistoryDAO().getHistoryChangeTimes(personID);
        } catch (DAOException e) {
            throw new ServiceException(e.getMessage(),e);
        }   
    }

    public EligibilityEnrollmentService getEligibilityEnrollmentService() 
	{
		return eligibilityEnrollmentService;
	}

	public void setEligibilityEnrollmentService(
			EligibilityEnrollmentService eligibilityEnrollmentService) 
	{
		this.eligibilityEnrollmentService = eligibilityEnrollmentService;
	}
	  /**
     * @return Returns the registryService.
     */
    public RegistryService getRegistryService()
    {
        return registryService;
    }

    /**
     * Sets registryService.
     * @param registryService 
     */
    public void setRegistryService(
    		RegistryService registryService)
    {
        this.registryService = registryService;
    }
}
