/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.ui.ee.action;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;

import java.math.BigDecimal;
import gov.va.med.esr.common.infra.ImpreciseDate;

import org.apache.commons.lang.ObjectUtils;

import gov.va.med.fw.conversion.ConversionServiceException;
import gov.va.med.fw.model.EntityKey;
import gov.va.med.fw.util.StringUtils;

import gov.va.med.esr.common.model.lookup.DecorationStatus;
import gov.va.med.esr.common.model.lookup.EligibilityStatus;
import gov.va.med.esr.common.model.lookup.EligibilityStatusPendVerfiReason;
import gov.va.med.esr.common.model.lookup.EligibilityType;
import gov.va.med.esr.common.model.lookup.Indicator;
import gov.va.med.esr.common.model.lookup.MonetaryBenefitType;
import gov.va.med.esr.common.model.lookup.AgentOrangeExposureLocation;
import gov.va.med.esr.common.model.lookup.PensionReasonCode;
import gov.va.med.esr.common.model.lookup.RadiationExposureMethod;
import gov.va.med.esr.common.model.lookup.PrisonerOfWarLocation;
import gov.va.med.esr.common.model.lookup.POWCampLocation;
import gov.va.med.esr.common.model.lookup.POWDataSource;
import gov.va.med.esr.common.model.lookup.POWDocumentType;
import gov.va.med.esr.common.model.lookup.DiagnosticExtremity;
import gov.va.med.esr.common.model.lookup.Disability;
import gov.va.med.esr.common.model.lookup.RejectionRemark;
import gov.va.med.esr.common.model.lookup.ServicePeriod;
import gov.va.med.esr.common.model.lookup.EligibilityVerificationSource;
import gov.va.med.esr.common.model.lookup.SpinalCordInjuryType;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.ee.AgentOrangeExposure;
import gov.va.med.esr.common.model.ee.EligibilityVerification;
import gov.va.med.esr.common.model.ee.HealthBenefitProfile;
import gov.va.med.esr.common.model.ee.IncompetenceRuling;
import gov.va.med.esr.common.model.ee.MedicaidFactor;
import gov.va.med.esr.common.model.ee.MilitaryService;
import gov.va.med.esr.common.model.ee.MonetaryBenefit;
import gov.va.med.esr.common.model.ee.MonetaryBenefitAward;
import gov.va.med.esr.common.model.ee.Pension;
import gov.va.med.esr.common.model.ee.PrisonerOfWar;
import gov.va.med.esr.common.model.ee.PurpleHeart;
import gov.va.med.esr.common.model.ee.POWEpisode;
import gov.va.med.esr.common.model.ee.RadiationExposure;
import gov.va.med.esr.common.model.ee.RatedDisability;
import gov.va.med.esr.common.model.ee.SHAD;
import gov.va.med.esr.common.model.ee.ServiceConnectionAward;
import gov.va.med.esr.common.model.ee.EnvironmentalContaminationExposure;
import gov.va.med.esr.common.model.ee.SpinalCordInjury;
import gov.va.med.esr.service.PersonHelperService;

import gov.va.med.esr.ui.common.service.LookupCacheService;
import gov.va.med.esr.ui.common.util.JspUtils;
import gov.va.med.esr.ui.common.util.DateUtils;

import gov.va.med.esr.ui.militaryservice.action.MilitaryServiceInfoForm;
import gov.va.med.esr.ui.util.ApplicationInitializer;
import gov.va.med.esr.ui.util.ConvertUtils;

/**
 * @author DNS   KATIKM Conversion service for PersonOverviewForm and Person Object
 */
public class EligibilityConversionService extends EligibilityEnrollmentConversionService
{
    public EligibilityConversionService()
    {
        super();
    }

    public void merge(Object source, Object target)
    throws Exception
	{
        LookupCacheService lookupCacheService = getLookupCacheService();
    	PersonHelperService helper = getPersonHelperService();
        if (source instanceof Person && target instanceof Person)
        {
        	Person currentPerson = (Person)source;
        	Person updatedPerson = (Person)target;

        	if (!ObjectUtils.equals(
        			getLookupCode(helper.getEligibilityStatus(currentPerson)),
					getLookupCode(helper.getEligibilityStatus(updatedPerson)))
				|| !ObjectUtils.equals(
					JspUtils.displayValue(getEligStatusDate(currentPerson), null),
					JspUtils.displayValue(getEligStatusDate(updatedPerson), null)))
        	{
                setEligVerSource(updatedPerson, (EligibilityVerificationSource)lookupCacheService.getByCodeFromCache(EligibilityVerificationSource.class, EligibilityVerificationSource.CODE_CEV.getName()));
        	}


        }
	}

    protected void convertBean(Object source, Object target)
        throws ConversionServiceException
    {
        PersonHelperService helper = getPersonHelperService();

        //convert the objects
        if (source instanceof Person)
        {
            try
            {
                Person person = (Person)source;
                if (target instanceof EligibilityViewForm)
                {
                    convertEligView(person, (EligibilityViewForm)target, helper);
                }
                else
                    if (target instanceof EligibilityEditActionForm)
                        convertEligEdit(person, (EligibilityEditActionForm)target, helper);
                    else if (target instanceof EligibilityEditReviewActionForm)
                        convertEligReview(person, (EligibilityEditReviewActionForm)target, helper);
                    else if (target instanceof ServicePeriodForm)
                    {
                    	ServicePeriodForm formBean = (ServicePeriodForm)target;
                    	formBean.setPrimaryElig(getPrimaryEligibilityType(person));
                    	formBean.setPeriodOfService(getPeriodOfService(person));
                    	formBean.setServicePeriodList(getServicePeriodList(
                    			getPrimaryEligibilityType(person)));
                    }
                    else
                    {
                        throw new ConversionServiceException("Type mismatch: Expecting EligibilityViewForm or EligibilityEditActionForm or EligibilityEditReviewActionForm, Received " +
                            target.getClass().getName());
                    }
            }
            catch (Exception ex)
            {
                throw new ConversionServiceException("Conversion Failed", ex);
            }
        }
        else
            if (source instanceof EligibilityEditActionForm)
            {
                try
                {
                    if (target instanceof Person)
                        convertEligEdit((EligibilityEditActionForm)source,
                            (Person)target, helper);
                }
                catch (Exception ex)
                {
                    throw new ConversionServiceException("Conversion Failed on convertEligEdit", ex);
                }
            }
            else if (source instanceof ServicePeriodForm && target instanceof Person)
            {
            	ServicePeriodForm formBean = (ServicePeriodForm)source;
            	Person person = (Person)target;

            	try {
					setPeriodOfService(person, formBean.getPeriodOfService(), getLookupCacheService());
				} catch (Exception e) {
		             throw new ConversionServiceException("Conversion Failed on convert period of service", e);
				}
            }
            else
            {
                throw new ConversionServiceException("Type mismatch: Expecting Person, Received " +
                    source.getClass().getName());
            }
    }

    private Vector getServicePeriodList(EligibilityType type) throws Exception
    {
        LookupCacheService lookupCacheService = getLookupCacheService();
        Collection list = lookupCacheService.getFromCache("gov.va.med.esr.common.model.lookup.ServicePeriod");
        Vector subList = new Vector();
		if (list != null)
		{
			for (Iterator iter = list.iterator(); iter.hasNext();)
			{
				ServicePeriod obj = (ServicePeriod)iter.next();
				if (obj.isSubSetForNonVeteranCode(type.getCode()))
					subList.add(obj);
			}
		}
		return subList;
    }

    private void convertEligView(Person person, EligibilityViewForm formBean, PersonHelperService helper)
        throws Exception
    {
    	formBean.setVeteranIndicator(person.getVeteran());
        formBean.setPrimaryElig(getPrimaryEligibilityDesc(person));
        formBean.setApplicationDate(getApplicationDate(person));
        formBean.setScPercentage(getServiceConnectedPercentage(person));
        formBean.setEnrollmentEffDate(getEnrollEffDate(helper.getEnrollmentDetermination(person)));
        formBean.setEffectiveDateCombinedRating(getEffectiveDateCombinedRating(person));
        formBean.setTotalCheck(getTotalCheckAmount(person));
        formBean.setEligStatus(helper.getEligibilityStatus(person));
        formBean.setEligVerMethod(getEligVerMethod(person));
        formBean.setEligStatusDate(getEligStatusDate(person));
        formBean.setAACIndicator(getAACIndicator(person));
        formBean.setEligVerSource(getEligVerSource(person));
        formBean.setEligVerSourceFacility(getEligVerSourceFacility(person));
        formBean.setMSDSQueryStatus(helper.getMSDSQueryStatus(person));

        formBean.setEligStatusPVReason(helper.getEligStatusPendingVerficationReason(person));
        formBean.setEligStatusPVReasonExplain(getEligStatusPendingVerfReasonExplain(person));

        //Health Benefit Plans
		//formBean.setCurrentNumberOfHealthBenefitPlans(currentNumberOfHealthBenefitPlans);
		//formBean.setCurrentNumberOfHealthBenefitPlans(10);
		HealthBenefitProfile hbp = person.getHealthBenefitProfile();
		if (hbp!=null) {
		      Set plans = hbp.getHealthBenefitPlans();
		      formBean.setCurrentNumberOfHealthBenefitPlans(plans.size());
		      //plans.addHealthBenefitPlan(newPlan);
		      //plans.removeHealthBenefitPlan(oldPlan);
		}
		else
		{
			formBean.setCurrentNumberOfHealthBenefitPlans(0);
		}

        //PH
        PurpleHeart ph = person.getPurpleHeart();
        if (ph == null || ph.getStatus() == null) {
        	formBean.setPhStatus(null);
        }
        else {
        	formBean.setPhStatus(ph.getStatus());
        }
        //POW
        PrisonerOfWar pow = person.getPrisonerOfWar();
        if (pow == null) {
            formBean.setPowIndicator(null);
            formBean.setPowEpisodes(null);
        }
        else {
            formBean.setPowIndicator(pow.getPowIndicator());
            formBean.setPowEpisodes(pow.getEpisodes());
        }

        formBean.setScDisbilities(getDisabilities(person));
        formBean.setOtherEligCodes(getOtherEligCodes(person));
        formBean.setOtherEligFactors(getOtherEligFactors(person));
        formBean.setIneligibilityFactor(person.getIneligibilityFactor());

        formBean.setIncomeTestDate(getIncomeTestDate(person));
        formBean.setIncomeTestFacility(getIncomeTestFacility(person));
        formBean.setIncomeTestStatus(getIncomeTestStatusDesc(person));
        formBean.setIncomeTestYear(getIncomeTestYear(person));
        formBean.setIncomeTestLastEdited(getIncomeTestLastEdited(person));
    }

    private void convertPow(EligibilityEditActionForm eeForm, PrisonerOfWar pow)
    {
    	eeForm.setPowInd(ConvertUtils.convertYesNoNoDataString(
    		(pow == null || pow.getPowIndicator() == null)? null : pow.getPowIndicator().toBoolean()));

    	eeForm.initPow();
    	if (pow != null)
    	{
    		Set powSet = pow.getEpisodes();
    		if (powSet != null)
    		{
    			for (Iterator iterator = powSet.iterator(); iterator.hasNext();)
    			{
    				Object data = iterator.next();
    				if (data != null && (data instanceof POWEpisode))
    				{
    					POWEpisode powEpisode = (POWEpisode)data;
    					Long days = null;
//    					//Only calculate if both are precise dates
						if (powEpisode.getReleaseDate() != null && powEpisode.getCaptureDate() != null)
    						days = DateUtils.getDays(powEpisode.getCaptureDate(), powEpisode.getReleaseDate(), true);
    					eeForm.addPow(//(pow.getEntityKey() == null)? "" : pow.getEntityKey().getKeyValueAsString(),
    							powEpisode.getEntityKey(),
								(powEpisode.getConfinementLocation() == null) ? "" : powEpisode.getConfinementLocation().getCode(),
								JspUtils.displayValue(powEpisode.getCaptureDate(), null),
								JspUtils.displayValue(powEpisode.getReleaseDate(), null),
								(days == null)? "" : days.toString(),
								(powEpisode.getDataSource() == null) ? "" : powEpisode.getDataSource().getCode(), //powSource
								(powEpisode.getDocumentType() == null) ? "" : powEpisode.getDocumentType().getCode(), //powDocumentType
								(powEpisode.getCampLocation() == null) ? "" : powEpisode.getCampLocation().getCode(), //powCampLocation
								(powEpisode.getCampLocation() == null) ? "" : powEpisode.getCampLocation().getCode(), //powCampCode
								(powEpisode.getCampLocation() == null) ? "" : powEpisode.getCampLocation().getName(), //powCampName
								(powEpisode.getCampLocation() == null) ? "" : powEpisode.getCampLocation().getDescription(), //powCampCity
								JspUtils.displayValue(powEpisode.getDateEntered(), null) //getDateEntered()
    					);
    				}
    			}
    		}
    	}
    }

    private void convertEligReview(Person person,
        EligibilityEditReviewActionForm eeForm,
        PersonHelperService helper) throws Exception
    {
        eeForm.setEnrollStatus(helper.getEnrollmentStatus(person));
        eeForm.setAppDate(getApplicationDate(person));
        eeForm.setEligStatus(helper.getEligibilityStatus(person));
        eeForm.setEligStatusDate(getEligStatusDate(person));
        eeForm.setEligVerSourceFacility(getEligVerSourceFacility(person));
        eeForm.setEligVerMethod(getEligVerMethod(person));
        eeForm.setPrimaryEligCode(getPrimaryEligibilityDesc(person));
        eeForm.setTotalCheckAmt(getTotalCheckAmount(person));
        eeForm.setOtherEligCodes(getOtherEligCodes(person));
        eeForm.setOtherEligFactors(getOtherEligFactors(person));
        eeForm.setEnrollmentPriority(getEnrollmentPriority(person));
        eeForm.setScIndicator(isServiceConnected(person));
        eeForm.setScPercentage(getServiceConnectedPercentage(person));
        eeForm.setEditedDate(getEnrollModifiedDate(person));
        eeForm.setEditedBy("");
        eeForm.setEligStatusPVReason(helper.getEligStatusPendingVerficationReason(person));
        eeForm.setEligStatusPVReasonExplain(getEligStatusPendingVerfReasonExplain(person));
        eeForm.setEligStatusDate(getEligStatusDate(person));
        

        Person proposedPerson = eeForm.getProposedPerson();
        eeForm.setEnrollStatusProposed(helper.getEnrollmentStatus(proposedPerson));
        eeForm.setApplicationDateProposed(getApplicationDate(proposedPerson));
        eeForm.setEligStatusProposed(helper.getEligibilityStatus(proposedPerson));
        eeForm.setEligStatusDateProposed(getEligStatusDate(proposedPerson));
        eeForm.setEligVerSourceFacilityProposed(getEligVerSourceFacility(proposedPerson));
        eeForm.setEligVerMethodProposed(getEligVerMethod(proposedPerson));
        eeForm.setPrimaryEligCodeProposed(getPrimaryEligibilityDesc(proposedPerson));
        eeForm.setTotalCheckAmtProposed(getTotalCheckAmount(proposedPerson));
        eeForm.setOtherEligCodesProposed(getOtherEligCodes(proposedPerson));
        eeForm.setOtherEligFactorsProposed(getOtherEligFactors(proposedPerson));
        eeForm.setEnrollmentPriorityProposed(getEnrollmentPriority(proposedPerson));
        eeForm.setScIndicatorProposed(isServiceConnected(proposedPerson));
        eeForm.setScPercentageProposed(getServiceConnectedPercentage(proposedPerson));
        eeForm.setEditedDateProposed(new Date());
        eeForm.setEditedByProposed("");

    }

    private void convertEligEdit(Person person,
        EligibilityEditActionForm eeForm,
        PersonHelperService helper) throws Exception
    {
    	eeForm.setDeathDate(JspUtils.displayValue(
                ((person.getDeathRecord() == null) ? null : person.getDeathRecord().getDeathDate()), null));

        //BirthDate
        eeForm.setBirthDate(JspUtils.displayValue(
            ((person.getBirthRecord() == null) ? null : person.getBirthRecord().getBirthDate()), null));
        //todayDate
        eeForm.setTodayDate(JspUtils.displayValue(new Date(), null));

        //Veteran Indicator
        eeForm.setVeteranIndicator(getVeteranIndicator(person));
        eeForm.setOldVeteranIndicator(getVeteranIndicator(person));

        //1. Eligibility Status
        EligibilityStatus eligStatus = helper.getEligibilityStatus(person);
        if (eligStatus == null)
            eeForm.setEligibilityStatus("");
        else
            eeForm.setEligibilityStatus(eligStatus.getCode());

        //2. Eligibility Status Date
        eeForm.setEligibilityStatusDate(JspUtils.displayValue(getEligStatusDate(person), null));
        eeForm.setOldEligibilityStatusDate(JspUtils.displayValue(getEligStatusDate(person), null));

        // seteligStatusPendingVerficationReason
 //       helper.setEligStatusPendingVerficationReason(eeForm.getEligStatusPendingVerficationReason() , person);  
        
        EligibilityStatusPendVerfiReason eligStatusReason = helper.getEligStatusPendingVerficationReason(person);
        if (eligStatusReason == null)
            eeForm.setEligStatusPendingVerficationReason("");
        else
            eeForm.setEligStatusPendingVerficationReason(eligStatusReason.getCode());
        
         // seteligStatusPendingVerfReasonExplain;        
        eeForm.setEligStatusPendingVerfReasonExplain(getEligStatusPendingVerfReasonExplain(person));
        
        //3. VerificationMethod
        eeForm.setVerificationMethod(getEligVerMethod(person));

        //4. SC Percentage
        eeForm.setServiceConnected(getServiceConnectedPercentage(person));
        eeForm.setEffectiveDateCombinedRating(JspUtils.displayValue(getEffectiveDateCombinedRating(person), null));

        //5. POW indicator
        convertPow(eeForm, person.getPrisonerOfWar());

        //9. 10. 11. PurpleHeart
        PurpleHeart ph = helper.getPurpleHeart(person);
        if (ph == null || ph.getStatus() == null)
        {
            eeForm.setPhStatus(null);
        }
        else
        {
            eeForm.setPhStatus(ph.getStatus().getCode());
        }

        //12. AidAttendance
        eeForm.setAidAttendance(ConvertUtils.convertYesNo(isAidAttendance(person)));

        //13. Housebound
        eeForm.setHousebound(ConvertUtils.convertYesNo(isHousebound(person)));

        //14. VaPension
        eeForm.setVaPension(ConvertUtils.convertYesNo(isVAPension(person)));
        eeForm.setOldvaPension(ConvertUtils.convertYesNo(isVAPension(person)));

        //15. Receiving VA Disability Compensation
        eeForm.setIsReceivingCompensation(ConvertUtils.convertYesNoUnknown(
            isReceivingVADisabilityCompensation(person)));

        //16. 17. totalCheckAmount
        BigDecimal checkAmount = getTotalCheckAmount(person);
        if (checkAmount == null)
        {
            eeForm.setTotalCheckAmount(null);
            eeForm.setTotalMonthlyCheckAmount(null);
        }
       	else if (checkAmount.equals(BigDecimal.valueOf(0)))
    	{
    		eeForm.setTotalCheckAmount("0");
    		eeForm.setTotalMonthlyCheckAmount("0");
    	}
    	else
    	{
	        eeForm.setTotalCheckAmount(checkAmount.toString());
	        eeForm.setTotalMonthlyCheckAmount(
	        	checkAmount.divide(BigDecimal.valueOf(12), 2, BigDecimal.ROUND_UP).toString());
    	}

        //18. Unemployable
        eeForm.setUnemployable(ConvertUtils.convertYesNo(isUnemployable(person)));

        //19. Permanent & Total
        eeForm.setPermanentTotal(ConvertUtils.convertYesNo(isPermanentTotal(person)));

        //20.
        eeForm.setPermanentTotalEffDate(JspUtils.displayValue(getPermanentTotalEffDate(person),
            null));

        //21. Rated Incompetent
        IncompetenceRuling incompetenceRuling = person.getIncompetenceRuling();
        if (incompetenceRuling == null)
        {
            eeForm.setRatedIncompetent(ConvertUtils.NULL_VALUE);
            eeForm.setCivilDate("");
            eeForm.setVaDate("");
        }
        else
        {
            eeForm.setCivilDate(JspUtils.displayValue(incompetenceRuling.getCivilRulingDate(), null));
            eeForm.setVaDate(JspUtils.displayValue(incompetenceRuling.getVaRulingDate(), null));
            eeForm.setRatedIncompetent(ConvertUtils.convertYesNoNoData(incompetenceRuling.isIncompetent()));
        }

        //23. Eligible For Medicaid
        eeForm.setEligibleForMedicaid(ConvertUtils.convertYesNoNoData(
            isEligibleForMedicaid(person)));

        //24. Date Medicaid Last Updated
        Date medicaidUpdateDate = getMedicaidUpdatedDate(person);
        if (medicaidUpdateDate != null)
        {
            eeForm.setMedicaidUpdatedDate(DateUtils.formatForEdit(medicaidUpdateDate, null));
        }

        //25. Ineligible Date
        Date serviceEntryDate = person.getMilitaryService() == null ? null :
            person.getMilitaryService().getServiceEntryDate();
        eeForm.setServiceEntryDate(JspUtils.displayValue(serviceEntryDate,null));
        eeForm.setIneligibleDate(JspUtils.displayValue(getIneligibleDate(person), null));

        //26. Ineligible Reason
        eeForm.setIneligibleReason(getIneligibleReason(person));

        //27. Ineligible VARO Decision
        eeForm.setIneligibleVARODecision(getIneligibleVARODecision(person));

        //28. Discharge Due To Disability
        eeForm.setDischargeDueDisability(ConvertUtils.convertYesNoNoData(
            getDischargeDueDisability(person)));

        //29. Military Disability Retirement
        eeForm.setDisabilityRetirementIndicator(ConvertUtils.convertYesNoNoData(
            getDisabilityRetirementIndicator(person)));

        //30. AgentOrangeExposure Location
        eeForm.setAgentOrangeLocation(getAgentOrangeLocation(person));

        //31. RadiationExposureMethod
        eeForm.setRadiationExposureMethod(getRadiationExposureMethod(person));

        //32. EnvironmentalContaminationExposure
        Indicator indicator = null;
        EnvironmentalContaminationExposure ece = getEnvironmentalContaminationExposure(person);
        if (ece != null)
        {
            indicator = ece.getEnvironmentalContaminationExposureIndicator();
        }
        eeForm.setEnvironmentalContaminationExposure(ConvertUtils.convertYesNo
            (indicator == null ? Boolean.FALSE : indicator.toBoolean()));

        //33. Rated SC Disabilities
        convertDisabilities(eeForm, person);


        //34. Non-Veteran Eligibilities
        eeForm.setPeriodOfService(getPeriodOfService(person));
        eeForm.setTricare(ConvertUtils.convertYesNo(isTricare(person)));
        eeForm.setSharingAgreement(ConvertUtils.convertYesNo(isSharingAgreement(person)));
        eeForm.setAlliedVeteranCountry(getAlliedVeteranCountry(person));
        eeForm.setChampa(ConvertUtils.convertYesNo(isChampa(person)));
        eeForm.setEmployee(ConvertUtils.convertYesNo(isEmployee(person)));
        eeForm.setCollateralOfVet(ConvertUtils.convertYesNo(isCollateralOfVet(person)));
        eeForm.setOtherFederalAgency(getOtherFederalAgency(person));

        //35. Camp Lejeune Veteran //CLV
        populateCampLejeune(eeForm, person);

        //CR 4510 Pension Data Group
        Pension p = getPension(person);

        if (p != null)
        {
        	eeForm.setPensionAwardEffectiveDate(JspUtils.displayValue(p.getEffectiveDate(),null));
        	eeForm.setPensionAwardReasonCode(p.getAwardReasonCode() == null ? "" :p.getAwardReasonCode().getCode());
        	eeForm.setPensionAwardTerminationDate(JspUtils.displayValue(p.getTerminationDate(),null));
        	eeForm.setPensionAwardTerminationReasonCode1(p.getTerminationReasonCode1() == null ? "" : p.getTerminationReasonCode1().getCode());
        	eeForm.setPensionAwardTerminationReasonCode2(p.getTerminationReasonCode2() == null ? "" : p.getTerminationReasonCode2().getCode());
        	eeForm.setPensionAwardTerminationReasonCode3(p.getTerminationReasonCode3() == null ? "" : p.getTerminationReasonCode3().getCode());
        	eeForm.setPensionAwardTerminationReasonCode4(p.getTerminationReasonCode4() == null ? "" : p.getTerminationReasonCode4().getCode());
        }
        //CCR10475
        else
        {
        	eeForm.setPensionAwardEffectiveDate("");
        	eeForm.setPensionAwardReasonCode("");
        	eeForm.setPensionAwardTerminationDate("");
        	eeForm.setPensionAwardTerminationReasonCode1("");
        	eeForm.setPensionAwardTerminationReasonCode2("");
        	eeForm.setPensionAwardTerminationReasonCode3("");
        	eeForm.setPensionAwardTerminationReasonCode4("");
        }

        eeForm.setSpinalCordInjury(person.getSpinalCordInjury() == null ? "" : person.getSpinalCordInjury().getSpinalCordInjuryType().getCode());
        eeForm.setNoseThroatRadium(getNoseThroatRadium(person));
    }

    private Pension getPension(Person person)
    {
    	if (person != null && person.getMonetaryBenefitAward() != null &&
    			person.getMonetaryBenefitAward().getVAPension() != null)
    	{
    		return person.getMonetaryBenefitAward().getVAPension().getPension();
    	}

    	return null;

    }
    private void convertDisabilities(EligibilityEditActionForm eeForm, Person person)
    {
        ServiceConnectionAward scAward = person.getServiceConnectionAward();
        eeForm.initDisability();
        if (scAward != null && scAward.getRatedDisabilities() != null)
        {
            Set disList = scAward.getRatedDisabilities();
            eeForm.setSelectedDisabilityIndexes(new int[disList.size()]);
            int index = 0;

            for (Iterator iterator = disList.iterator(); iterator.hasNext();)
            {
                Object data = iterator.next();
                if (data instanceof RatedDisability)
                {
                    RatedDisability rd = (RatedDisability)data;
                    if (rd != null && rd.getDisability() != null)
                    {
                        String idString = (rd.getEntityKey() == null) ? "" : rd.getEntityKey().getKeyValueAsString();
                        eeForm.addDisability(rd.getEntityKey(),
                            idString,
                            (rd.getDisability() == null) ? "" : rd.getDisability().getCode(),
                            (rd.getDisability() == null) ? "" : rd.getDisability().getName(),
                            (rd.getPercentage() == null ? "" : rd.getPercentage().toString()),
                            (rd.getDiagnosticExtremity() == null ? "" : rd.getDiagnosticExtremity().getCode()),
                            JspUtils.displayValue(rd.getOriginalEffectiveRatingDate(), null),
                            JspUtils.displayValue(rd.getRatingDate(), null));
                        if (index < disList.size())
                        {
                            eeForm.getSelectedDisabilityIndexes()[index] = index;
                            index++;
                        }
                    }
                }
            }
        }
    }

    private void convertEligEdit(EligibilityEditActionForm eeForm,
        Person person,
        PersonHelperService helper) throws Exception
    {
        LookupCacheService lookupCacheService = getLookupCacheService();

        if (person.getEligibilityVerification() == null &&
            (eeForm.getEligibilityStatus() != null
            || eeForm.getEligibilityStatusDate() != null
            || eeForm.getVerificationMethod() != null))
        {
            person.setEligibilityVerification(new EligibilityVerification());
        }

        //Veteran Indicator
        setVeteranIndicator(person, eeForm.getVeteranIndicator());

        //1. Eligibility Status
        helper.setEligibilityStatus(eeForm.getEligibilityStatus(), person);

        //2. Eligibility Status Date
        setEligStatusDate(person, eeForm.getEligibilityStatusDate());

        //3. VerificationMethod
        setEligVerMethod(person, eeForm.getVerificationMethod());
        
        // seteligStatusPendingVerficationReason
        helper.setEligStatusPendingVerficationReason(eeForm.getEligStatusPendingVerficationReason() , person);  
        
         // seteligStatusPendingVerfReasonExplain;
        
        setEligStatusPendingVerfReasonExplain(person, eeForm.getEligStatusPendingVerfReasonExplain());

        //Service Connection Award
        if (person.isVeteran() != null && person.isVeteran().booleanValue()) {

	        //4. SC Percentage
	        setServiceConnectedPercentage(person, eeForm.getServiceConnected());
	        setEffectiveDateCombinedRating(person, eeForm.getEffectiveDateCombinedRating());

	        //5. POW indicator
	        convertPow(person, eeForm, helper);

	        //9. 10. 11. PurpleHeart
	        //Read only

	        //12. AidAttendance
	        setMonetaryBenefit(person, eeForm.getAidAttendance(),
	            (MonetaryBenefitType)lookupCacheService.getByCodeFromCache(MonetaryBenefitType.class,
	                MonetaryBenefitType.CODE_AID_AND_ATTENDANCE.getName()));

	        //13. Housebound
	        setMonetaryBenefit(person, eeForm.getHousebound(),
	            (MonetaryBenefitType)lookupCacheService.getByCodeFromCache(MonetaryBenefitType.class,
	                MonetaryBenefitType.CODE_HOUSEBOUND.getName()));

	        //14. VaPension
	        setMonetaryBenefit(person, eeForm.getVaPension(),
	            (MonetaryBenefitType)lookupCacheService.getByCodeFromCache(MonetaryBenefitType.class,
	                MonetaryBenefitType.CODE_VA_PENSION.getName()));

	        //15. Receiving VA Disability Compensation
	        setMonetaryBenefit(person, eeForm.getIsReceivingCompensation(),
	            (MonetaryBenefitType)lookupCacheService.getByCodeFromCache(MonetaryBenefitType.class,
	                MonetaryBenefitType.CODE_DISABILITY_COMPENSATION.getName()));

	        //16. totalCheckAmount
	        //17. TotalMonthlyCheckAmount should be updated together with TotalCheckAmount
	        //by JavaScript
	        setTotalCheckAmount(person, eeForm.getTotalCheckAmount());

	        //18. Unemployable
	        setUnemployable(person, eeForm.getUnemployable());

	        //19. PermanentAndTotal
	        setPermanentAndTotal(person, eeForm.getPermanentTotal());

	        //20. PermanentTotalEffDate
	        setPermanentAndTotalEffDate(person, eeForm.getPermanentTotalEffDate());

	        //23. Eligible For Medicaid
	        //24. Date Medicaid Last Updated
	        ImpreciseDate dateWithTimeImpreciseDate =
	            DateUtils.getImpreciseDate(eeForm.getMedicaidUpdatedDate(), true);
	        setEligibleForMedicaid(person, eeForm.getEligibleForMedicaid(),
	        	(dateWithTimeImpreciseDate == null)? null : dateWithTimeImpreciseDate.getDate());

	        //28. Discharge Due To Disability
	        setDischargeDueDisability(person,
	        	ConvertUtils.convertBoolean(eeForm.getDischargeDueDisability()));

	        //29. Military Disability Retirement
	        setDisabilityRetirementIndicator(person,
	            ConvertUtils.convertBoolean(eeForm.getDisabilityRetirementIndicator()));

	        //30. AgentOrangeExposure Location
	        setAgentOrangeExposure(person,
	            (AgentOrangeExposureLocation)lookupCacheService.getByCodeFromCache(AgentOrangeExposureLocation.class,
	                eeForm.getAgentOrangeLocation()));

	        //31. RadiationExposureMethod
	        setRadiationExposureMethod(person,
	            (RadiationExposureMethod)lookupCacheService.getByCodeFromCache(RadiationExposureMethod.class,
	                eeForm.getRadiationExposureMethod()));

	        //32. EnvironmentalContaminationExposure
	        setEnvironmentalContaminationExposure(person,
	            eeForm.getEnvironmentalContaminationExposure());

	        //33. Rated SC Disabilities
	        convertDisabilities(person, eeForm, helper);
	        //35. Camp Lejeune //CLV
	        updateCLVFromGUI(eeForm,person);
        }
        else {
        	//set non veteran values
        	setNonVeteranPropties(person, eeForm);
        }

        //Common fields for veteran and non-veteran
        //21. Rated Incompetent
        setRatedIncompetent(person, eeForm.getRatedIncompetent());

        //22. Incompetent Civil Date, Incompetent VA Date
        setCivilDate(person, DateUtils.getImpreciseDate(eeForm.getCivilDate()));
        setVaDate(person, DateUtils.getImpreciseDate(eeForm.getVaDate()));

        //25. Ineligible Date
        setIneligibleDate(person, eeForm.getIneligibleDate());

        //26. Ineligible Reason
        setIneligibleReason(person, eeForm.getIneligibleReason());

        //27. Ineligible VARO Decision
        setIneligibleVARODecision(person, eeForm.getIneligibleVARODecision());

        //34. Non-Veteran Eligibilities
        person.setReceivedPrimaryEligiblity(null);
        person.removeAllReceivedSecondaryEligibilities();
        String secondElig = eeForm.getTricare();
        if (secondElig != null && secondElig.equalsIgnoreCase(ApplicationInitializer.YES_VALUE))
            setNonVeteranElig(person, lookupCacheService,
                EligibilityType.TRICARE_CHAMPUS.getName());

        secondElig = eeForm.getSharingAgreement();
        if (secondElig != null && secondElig.equalsIgnoreCase(ApplicationInitializer.YES_VALUE))
            setNonVeteranElig(person, lookupCacheService,
                EligibilityType.SHARING_AGREEMENT.getName());

//	    //eeForm.setAlliedVeteranCountry(EligibilityVOAdapter.getAlliedVeteranCountry(person));
        secondElig = eeForm.getAlliedVeteranCountry();
        if (secondElig != null && secondElig.trim().length() > 0)
        	setAlliedCountry(person, lookupCacheService, secondElig);

        secondElig = eeForm.getChampa();
        if (secondElig != null && secondElig.equalsIgnoreCase(ApplicationInitializer.YES_VALUE))
            setNonVeteranElig(person, lookupCacheService, EligibilityType.CHAMPVA.getName());

        secondElig = eeForm.getEmployee();
        if (secondElig != null && secondElig.equalsIgnoreCase(ApplicationInitializer.YES_VALUE))
            setNonVeteranElig(person, lookupCacheService, EligibilityType.EMPLOYEE.getName());

        secondElig = eeForm.getCollateralOfVet();
        if (secondElig != null && secondElig.equalsIgnoreCase(ApplicationInitializer.YES_VALUE))
            setNonVeteranElig(person, lookupCacheService,
                EligibilityType.COLLATERAL_OF_VETERAN.getName());

//	    //eeForm.setOtherFederalAgency(EligibilityVOAdapter.getOtherFederalAgency(person));
        secondElig = eeForm.getOtherFederalAgency();
        if (secondElig != null && secondElig.trim().length() > 0)
        	setOtherFederalAgency(person, lookupCacheService, secondElig);

        //set POS for primary non-veteran code
        setPeriodOfService(person, eeForm.getPeriodOfService(), lookupCacheService);

        //CR4510 Pension Data Group
        setPensionDataFromFormToPerson(person, eeForm, lookupCacheService);

        setSpinalCordInjury(person, eeForm.getSpinalCordInjury(), eeForm, lookupCacheService);
        setNoseThroatRadium(person, eeForm.getNoseThroatRadium());
    }

    private void setSpinalCordInjury(Person person, String sciString, EligibilityEditActionForm eeForm,
    		LookupCacheService lookupCacheService) throws Exception {
    	SpinalCordInjury spi = person.getSpinalCordInjury();
    	if (spi == null) {
    		spi = new SpinalCordInjury();
    		person.setSpinalCordInjury(spi);
    	}
    	spi.setSpinalCordInjuryType((SpinalCordInjuryType)lookupCacheService.getByCodeFromCache(SpinalCordInjuryType.class, eeForm.getSpinalCordInjury()));
    }


    private void setPensionDataFromFormToPerson(Person person, EligibilityEditActionForm eeForm, LookupCacheService lookupCacheService)
    	throws Exception
    {
    	//form has Pension Data Group
		MonetaryBenefitAward awd = person.getMonetaryBenefitAward();
		if ( awd == null)
		{
			awd = new MonetaryBenefitAward();
			awd.setPerson(person);
			person.setMonetaryBenefitAward(awd);
		}

		MonetaryBenefit ben = awd.getVAPension();
		if ( ben == null)
		{
			ben = new  MonetaryBenefit();
			ben.setMonetaryBenefitAward(awd);
			ben.setType((MonetaryBenefitType)lookupCacheService.getByCodeFromCache(MonetaryBenefitType.class, MonetaryBenefitType.CODE_VA_PENSION.getCode()));

			awd.addMonetaryBenefit(ben);
		}

		Pension p = ben.getPension();
		if (p == null)
		{
			p = new Pension();
			p.setMonetaryBenefit(ben);

			ben.setPension(p);
		}

		p.setEffectiveDate(DateUtils.getDate(eeForm.getPensionAwardEffectiveDate()));
		p.setAwardReasonCode((PensionReasonCode)lookupCacheService.getByCodeFromCache(PensionReasonCode.class, eeForm.getPensionAwardReasonCode()));
		p.setTerminationDate(DateUtils.getDate(eeForm.getPensionAwardTerminationDate()));
		p.setTerminationReasonCode1((PensionReasonCode)lookupCacheService.getByCodeFromCache(PensionReasonCode.class, eeForm.getPensionAwardTerminationReasonCode1()));
		p.setTerminationReasonCode2((PensionReasonCode)lookupCacheService.getByCodeFromCache(PensionReasonCode.class, eeForm.getPensionAwardTerminationReasonCode2()));
		p.setTerminationReasonCode3((PensionReasonCode)lookupCacheService.getByCodeFromCache(PensionReasonCode.class, eeForm.getPensionAwardTerminationReasonCode3()));
		p.setTerminationReasonCode4((PensionReasonCode)lookupCacheService.getByCodeFromCache(PensionReasonCode.class, eeForm.getPensionAwardTerminationReasonCode4()));
    }
    private void convertPowEpisode(POWEpisode pow, EligibilityEditActionForm eeForm, int index)
    	throws Exception
    {
        LookupCacheService lookupCacheService = getLookupCacheService();

        String loc = eeForm.getPowConfinementLocation(index);
        pow.setConfinementLocation((PrisonerOfWarLocation)lookupCacheService.getByCodeFromCache(
                PrisonerOfWarLocation.class, loc));
        pow.setCaptureDate(DateUtils.getImpreciseDate(eeForm.getPowCaptureDate(index)));
        pow.setReleaseDate(DateUtils.getImpreciseDate(eeForm.getPowReleaseDate(index)));
        if ((pow.getCaptureDate() == null) || (pow.getReleaseDate() == null))
        {
            pow.setNumberOfDaysInCaptivity(null);
        }
        else
        {   //Only calculate if both are precise dates
        	Long days = DateUtils.getDays(pow.getCaptureDate(), pow.getReleaseDate(), true);
            pow.setNumberOfDaysInCaptivity((days == null)? null : new Integer(days.intValue()));
        }
        pow.setDataSource((POWDataSource)lookupCacheService.getByCodeFromCache(
        		POWDataSource.class, eeForm.getPowSource(index)));
        pow.setDocumentType((POWDocumentType)lookupCacheService.getByCodeFromCache(
        		POWDocumentType.class, eeForm.getPowDocumentType(index)));
        pow.setCampLocation((POWCampLocation)lookupCacheService.getByCodeFromCache(
        		POWCampLocation.class, eeForm.getPowCampLocation(index)));

        return;
    }

    private void convertPow(Person person,
        EligibilityEditActionForm eeForm,
        PersonHelperService helper) throws Exception
		{
            if(StringUtils.isNotEmpty(eeForm.getPowInd())) {

            }

    	String powInd = ConvertUtils.convertIndicator(eeForm.getPowInd());
    	if (powInd == null || StringUtils.equals(powInd,Indicator.UNKNOWN.getCode()))
    	{
    		person.setPrisonerOfWar(null);
    		return;
    	}
    	else
    	{
			if (person.getPrisonerOfWar() == null)
				person.setPrisonerOfWar(new PrisonerOfWar());

			PrisonerOfWar pow = person.getPrisonerOfWar();
			pow.setPowIndicator((Indicator)this.getLookupCacheService().getByCodeFromCache(Indicator.class,powInd));

    		if (eeForm.getPowIdList() == null || eeForm.getPowIdList().isEmpty())
    			pow.removeAllEpisodes();
    		else
    		{
    			ArrayList updatedPowEpisodes = new ArrayList();

    			for (int i = 0; i < eeForm.getPowIdList().size(); i++)
    			{
    				EntityKey id = eeForm.getPowId(i);
    				String loc = eeForm.getPowConfinementLocation(i);
    				ImpreciseDate capDate = DateUtils.getImpreciseDate(eeForm.getPowCaptureDate(i));
    				ImpreciseDate relDate = DateUtils.getImpreciseDate(eeForm.getPowReleaseDate(i));
    				if (id != null) //current epo
    				{
    					POWEpisode powEpisode = pow.getEpisodeByEntityKey(id);
    					if (powEpisode != null)
    					{
    						if ((loc == null || loc.length() == 0) && capDate == null && relDate == null)
    						{
    							pow.removeEpisodeByEntityKey(id);
    						}
    						else
    						{
    							convertPowEpisode(powEpisode, eeForm, i);
    							updatedPowEpisodes.add(powEpisode);
    						}
    					}
    					else
    					{
    						//Error. id should always get an object
    					}
    				}
    				else if (loc != null && loc.length() > 0 && capDate != null && relDate != null)
    				{ //User just added
    					POWEpisode powEpisode = new POWEpisode();
    					convertPowEpisode(powEpisode, eeForm, i);

    					updatedPowEpisodes.add(powEpisode);
    				}
    			}
    			//remove all others in person but not on form
    			pow.removeAllEpisodes();
    			for (Iterator iterator = updatedPowEpisodes.iterator(); iterator.hasNext();)
    			{
    				POWEpisode powEpisode = (POWEpisode)iterator.next();
    				pow.addEpisode(powEpisode);
    			}
    		}
    	}
		}

    private void convertDisabilities(Person person,
        EligibilityEditActionForm eeForm,
        PersonHelperService helper) throws Exception
    {
        LookupCacheService lookupCacheService = getLookupCacheService();

        ServiceConnectionAward scAward = person.getServiceConnectionAward();
        //int selectedIdIndex = 0;
        List remainingDisabilities = new ArrayList();

        if (scAward != null)
        {
        	// CCR11158 -- for Add a Person, person's existing disabilities won't have Ids, so
        	// get by EntityKey won't work.  Changing logic to clear Person's RatedDisability list, and
        	// then add it all back.
            if (eeForm.getSelectedDisabilityIndexes() != null || eeForm.getSelectedDisabilityIndexes().length != 0)
            {
                for (int i = 0; i < eeForm.getSelectedDisabilityIndexes().length; i++)
                {
                	int index = eeForm.getSelectedDisabilityIndexes()[i];
                	//String idString = eeForm.getDisabilityIdStrings(index);

                	//getDisabilityIdList
                    EntityKey id = eeForm.getDisabilityId(index);
                    //String idString = eeForm.getDisabilityIdStrings(i);
                    //String selectedIdString = null;
                    //if (selectedIdIndex < eeForm.getSelectedDisabilityIds().length)
                    //    selectedIdString = eeForm.getSelectedDisabilityIds()[selectedIdIndex];

                    //if (id != null && idString != null && !idString.equals(selectedIdString))
                    //{ //If user deselected this item
               //         scAward.removeRatedDisabilityByEntityKey(id);
                      //  continue;
                    //}
                    //else
                      //  if (idString != null && idString.equals(selectedIdString))
                      //  {
                    RatedDisability dis = (id == null) ? null : scAward.getRatedDisabilityByEntityKey(id);
                    if (dis == null)
                    {
                        Disability disability = (Disability)lookupCacheService.getByCodeFromCache(
                        		Disability.class, eeForm.getDisabilityCodes(index));
                        if (disability == null)
                        	continue;
                        else
                        {
                            dis = new RatedDisability();
                            scAward.addRatedDisability(dis);
                            dis.setDisability(disability);
                        }
                    }

                    DiagnosticExtremity de = (DiagnosticExtremity)lookupCacheService.getByCodeFromCache(
                            DiagnosticExtremity.class, eeForm.getDiagnosticExtremity(index));
                    dis.setDiagnosticExtremity(de);
                    dis.setPercentage(JspUtils.parseInt(eeForm.getPercentage(index)));
                    dis.setOriginalEffectiveRatingDate(DateUtils.getImpreciseDate(eeForm.getOriginalEffectiveDate(index)));
                    dis.setRatingDate(DateUtils.getImpreciseDate(eeForm.getCurrentEffectiveDate(index)));

                    remainingDisabilities.add(dis);
                }
             }

            scAward.removeAllRatedDisability();
            for (Iterator iterator = remainingDisabilities.iterator(); iterator.hasNext();)
            {
            	RatedDisability disability = (RatedDisability)iterator.next();
            	scAward.addRatedDisability(disability);
            }
        }
    }

    private void setNonVeteranPropties(Person person, EligibilityEditActionForm eeForm) throws Exception {
    	//Service connection Award
    	ServiceConnectionAward scAward = person.getServiceConnectionAward();
    	if (scAward != null){
    		scAward.setServiceConnectedPercentage(null);
    		if (scAward.getServiceConnectedIndicator() != null &&
    				scAward.getServiceConnectedIndicator().booleanValue()) {
    			scAward.setServiceConnectedIndicator(Boolean.FALSE);
    		}
    		if (scAward.getUnemployable() != null && scAward.getUnemployable().booleanValue()){
    			scAward.setUnemployable(Boolean.FALSE);
    		}
    		if (scAward.getPermanentAndTotal() != null && scAward.getPermanentAndTotal().booleanValue()){
    			scAward.setPermanentAndTotal(Boolean.FALSE);
    			scAward.setPermanentAndTotalEffectiveDate(null);
    		}
    		scAward.removeAllRatedDisability();
    	}
    	Indicator noIndicator = (Indicator) getLookupCacheService().getByCodeFromCache(
    			Indicator.class,Indicator.NO.getCode());

    	//Monitary Benefit set No if indicator is set to Yes
    	MonetaryBenefitAward mba = person.getMonetaryBenefitAward();
    	if (mba != null){
    		Set monetaryBenefits = mba.getMonetaryBenefits();
    		for (Iterator i=monetaryBenefits.iterator(); i.hasNext();){
    			MonetaryBenefit monetaryBenefit = (MonetaryBenefit) i.next();
    			if (monetaryBenefit.getMonetaryBenefitIndicator() != null &&
    		        Indicator.YES.getCode().equals(
    		        		monetaryBenefit.getMonetaryBenefitIndicator().getCode())){
    				monetaryBenefit.setMonetaryBenefitIndicator(noIndicator);
    			}
    		}
    		mba.setCheckAmount(null);
    	}
    	//Military Service
        MilitaryService militaryService = person.getMilitaryService();
        if (militaryService != null) {
            militaryService.setCombatVeteranEligibilityEndDate(null);
            if (militaryService.getDisabilityRetirementIndicator() != null &&
            		militaryService.getDisabilityRetirementIndicator().booleanValue()) {
            	militaryService.setDisabilityRetirementIndicator(Boolean.FALSE);
            }
            if (militaryService.getDischargeDueToDisability() != null &&
            		militaryService.getDischargeDueToDisability().booleanValue()) {
            	militaryService.setDischargeDueToDisability(Boolean.FALSE);
            }
        }

        // Set SHAD to No
        SHAD shad = (SHAD)person.getShad();
        if ((shad != null) && (shad.getShadIndicator() != null) &&
            (Indicator.YES.getCode().equals(shad.getShadIndicator().getCode())))
        {
            shad.setShadIndicator(noIndicator);
        }

        //Agent Orange Exposure
        AgentOrangeExposure aoe = person.getAgentOrangeExposure();
        if (aoe != null && aoe.getAgentOrangeExposureIndicator() != null &&
        		Indicator.YES.getCode().equals(aoe.getAgentOrangeExposureIndicator().getCode())){
        	aoe.setAgentOrangeExposureIndicator(noIndicator);
        	aoe.setLocation(null);
        }
        //Radiation exposure
        RadiationExposure rexp = person.getRadiationExposure();
        if (rexp != null && rexp.getRadiationExposureIndicator() != null &&
        		Indicator.YES.getCode().equals(rexp.getRadiationExposureIndicator().getCode())){
        	rexp.setRadiationExposureIndicator(noIndicator);
        	rexp.setExposureMethod(null);
        }
        //SW Asia conditions (Environmental Contamination Exposure)
        EnvironmentalContaminationExposure eexp = person.getEnvironmentalContaminationExposure();
        if (eexp != null && eexp.getEnvironmentalContaminationExposureIndicator() != null &&
        		Indicator.YES.getCode().equals(eexp.getEnvironmentalContaminationExposureIndicator().getCode())){
        	eexp.setEnvironmentalContaminationExposureIndicator(noIndicator);
        }

        //Update Purple Heart
        PurpleHeart ph = person.getPurpleHeart();
        if (ph != null && ph.getPhIndicator() != null && ph.getPhIndicator().booleanValue())
        {
            ph.setPhIndicator(Boolean.FALSE);
            ph.setStatus((DecorationStatus)getLookupCacheService().getByCodeFromCache(
                DecorationStatus.class, DecorationStatus.CODE_REJECTED.getName()));
            ph.setRejectionRemark((RejectionRemark)getLookupCacheService().getByCodeFromCache(
            	RejectionRemark.class, RejectionRemark.CODE_ENTERED_IN_ERROR.getName()));
        }
        //POW
        PrisonerOfWar pow = person.getPrisonerOfWar();
        if (pow != null && pow.getPowIndicator() != null &&
        		Indicator.YES.getCode().equals(pow.getPowIndicator().getCode())) {
        	pow.setPowIndicator(noIndicator);
            pow.setIcn(null);
            pow.setDateEntered(null);
            pow.setUser(null);
        	pow.removeAllEpisodes();
        }
        //Medicaid factor set no if yes and update date
        MedicaidFactor mf = person.getMedicaidFactor();
        if (mf != null && mf.isEligibleForMedicaid() != null &&
        		mf.isEligibleForMedicaid().booleanValue()) {
        	mf.setEligibleForMedicaid(Boolean.FALSE);
        	mf.setLastUpdateDate(DateUtils.getCurrentDate());
        }
    }
}
