/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.common.ui.conversion;

// Java Classes

// Library Classes

// Framework Classes
import gov.va.med.esr.common.model.financials.DependentFinancials;
import gov.va.med.esr.common.model.financials.RelationFinancials;
import gov.va.med.esr.common.model.financials.SpouseFinancials;
import gov.va.med.esr.common.model.party.Address;
import gov.va.med.esr.common.model.person.Employment;
import gov.va.med.esr.common.model.person.Name;
import gov.va.med.esr.common.model.person.Relation;
import gov.va.med.esr.common.model.person.SSN;
import gov.va.med.esr.common.model.person.Spouse;
import gov.va.med.esr.common.ui.form.DependentFinancialInfoBean;
import gov.va.med.esr.common.ui.form.RelationFinancialInfoBean;
import gov.va.med.esr.common.ui.form.SpouseFinancialInfoBean;
import gov.va.med.esr.common.util.CommonDateUtils;
import gov.va.med.esr.common.util.CommonJspUtils;
import gov.va.med.fw.conversion.ConversionServiceException;
import gov.va.med.fw.util.StringUtils;

import java.math.BigDecimal;

/**
 * An implementation of the conversion service in the common package layer with only the personToForm conversion.
 * 
 * @author DNS   chenj2
 */
public class CommonFinancialsDependentConversionService extends CommonConversionServiceImpl {

    public final static String LIVED_WITH_VETERAN      = "Lived with veteran last calendar year";
    public final static String DIDNT_LIVE_WITH_VETERAN = "Did not live with veteran last calendar year";

    /**
     * Default constructor.
     */
    public CommonFinancialsDependentConversionService() {}

    /**
     * Converts between a Person object that contains the financial information
     * and the FinancialDetailsForm.
     * 
     * @param source
     *            the source object
     * @param target
     *            the target object
     * 
     * @throws gov.va.med.fw.conversion.ConversionServiceException
     *             if any errors were encountered during the conversion.
     */
    protected void convertBean(Object source, Object target) throws ConversionServiceException {
        // subclass override
    }

    public void convertSpouseFinancialsToBean(SpouseFinancials spFins, SpouseFinancialInfoBean bean) {
        StringBuffer dependencyFactors = new StringBuffer();

        if (spFins != null) {
            // financials

            // get id
            convertFinancialsId(spFins, bean);
            convertValidDependent(spFins, bean);
            convertLivedWithVeteran(spFins, bean, dependencyFactors);

            // spousal support amt
            BigDecimal spouseAmt = spFins.getFinancialStatement() != null ? spFins.getFinancialStatement().getContributionToSpouse() : null;
            if (spouseAmt != null)
                bean.setContributedToSupport(spouseAmt.toString());

            // amount contributed to spouse indicator
            if( spFins.getFinancialStatement() != null){
                bean.setContributedToSpouseInd(getYesNoNoData(spFins.getFinancialStatement().getContributedToSpouseInd()));  
               
            }
            
            bean.setDependencyFactors(dependencyFactors.toString());
            bean.setActive(spFins.isActive());
            // spouse info
            convertRelationToBean(spFins.getReportedOn(), bean);
        }
    }

    public void convertDependentFinancialsToBean(DependentFinancials depFin, DependentFinancialInfoBean bean) {
        StringBuffer dependencyFactors = new StringBuffer();

        if (depFin != null) {
            // get id
            convertFinancialsId(depFin, bean);
            convertValidDependent(depFin, bean);
            
            bean.setIncapableOfSelfSupport(getYesNoNoData(depFin.getIncapableOfSelfSupport()));
            if (Boolean.TRUE.equals(depFin.getIncapableOfSelfSupport())) {
                dependencyFactors.append("Child incapable of self support").append("<br>");
            }
            
            bean.setHasIncome(getYesNoNoData(depFin.getHasIncome()));
            if (Boolean.TRUE.equals(depFin.getHasIncome())) {
                dependencyFactors.append("Child has Income").append("<br>");
            }
            
            bean.setContributedToSupport(getYesNoNoData(depFin.getContributedToSupport()));
            if (Boolean.TRUE.equals(depFin.getContributedToSupport())) {
                dependencyFactors.append("Contributed to child support").append("<br>");
            }

            bean.setAttendedSchool(getYesNoNoData(depFin.getAttendedSchool()));
            if (Boolean.TRUE.equals(depFin.getAttendedSchool())) {
                dependencyFactors.append("Child in school").append("<br>");
            }
            
            convertLivedWithVeteran(depFin, bean, dependencyFactors);            
            
            bean.setIncomeAvailableToPatient(getYesNoNoData(depFin.getIncomeAvailableToPatient()));            
            if (Boolean.TRUE.equals(depFin.getIncomeAvailableToPatient())) {
                dependencyFactors.append("Child has available income").append("<br>");
            }
            // amount contributed
            if (depFin.getAmountContributedToSupport() != null)
                bean.setAmtContributed(depFin.getAmountContributedToSupport().toString());

            bean.setDependencyFactors(dependencyFactors.toString());
            bean.setActive(depFin.isActive());
            // dependent info
            convertRelationToBean(depFin.getReportedOn(), bean);
            
            // set amount contributed to spouse for UI.
           /* if (Boolean.TRUE.equals(depFin.get) {
                bean.setContributedToSpouseInd(contributedToSpouseInd);
            }*/
            
        }
    }

    private void convertFinancialsId(RelationFinancials ftmt, RelationFinancialInfoBean bean) {
         bean.setFinancialsId(ftmt.getEntityKey() == null? null : ftmt.getEntityKey().getKeyValueAsString());
    }

    private void convertValidDependent(RelationFinancials fin, RelationFinancialInfoBean bean) {
        // dependentFinancials info
        Boolean validDep = fin.getValidDependent();
        bean.setValidDependent(validDep == null ? "Undetermined" : validDep.booleanValue() ? "Yes" : "No");
    }

    private void convertLivedWithVeteran(RelationFinancials fin, RelationFinancialInfoBean bean, StringBuffer dependencyFactors) {
        bean.setLivedWithVeteran(getYesNoNoData(fin.getLivedWithPatient()));            
        if (Boolean.TRUE.equals(fin.getLivedWithPatient())) {
            dependencyFactors.append(LIVED_WITH_VETERAN).append("<br>");
        }
        else if (Boolean.FALSE.equals(fin.getLivedWithPatient())) {
            dependencyFactors.append(LIVED_WITH_VETERAN).append("<br>");
        }
    }
    
 
    private void convertRelationToBean(Relation relation, RelationFinancialInfoBean bean) {
        if (relation != null && bean != null) {
            convertIdentifier(relation, bean);
            convertNames(relation, bean);
            convertDates(relation, bean);
            convertRelationship(relation, bean);
            convertGender(relation, bean);
            convertSsns(relation, bean);
            if (relation instanceof Spouse) {
                convertSpouseToBean((Spouse)relation, (SpouseFinancialInfoBean)bean);
            }
        }
    }
    
    private void convertSpouseToBean(Spouse spouse, SpouseFinancialInfoBean spouseInfoBean) {

        spouseInfoBean.setMaidenName(spouse.getMaidenName());
        Employment employment = spouse.getEmployment();
        if (employment != null ) {
            spouseInfoBean.setEmploymentStatus(getLookupCode(employment.getEmploymentStatus()));
            spouseInfoBean.setOnFileEmploymentStatus(getLookupCode(employment.getEmploymentStatus()));
            spouseInfoBean.setOccupation(employment.getOccupation());
            spouseInfoBean.setEmployerName(employment.getEmployerName());
            spouseInfoBean.setEmployerAddress(CommonJspUtils.displayAddress(employment.getEmployerAddress()));
            spouseInfoBean.setEmployerPhone(employment.getEmployerPhone());
            spouseInfoBean.setRetirementDate(CommonDateUtils.format(employment.getRetirementDate(), null));
        }
        Address address = spouse.getAddress();
        spouseInfoBean.setAddress(CommonJspUtils.displayAddress(address));
          if (address != null && address.getChangeDate() != null)
        {
              spouseInfoBean.setAddressChangeDate(CommonDateUtils.formatWithTime(address.getChangeDate(), null));
        }  

        spouseInfoBean.setPhone(CommonJspUtils.displayPhone(spouse.getHomePhone()));
    }
 
    private void convertIdentifier(Relation relation, RelationFinancialInfoBean bean) {
        bean.setIdentifier(relation.getEntityKey()==null ? null : relation.getEntityKey().getKeyValueAsString());
    }

    private void convertDates(Relation relation, RelationFinancialInfoBean bean) {
        if (relation.getDob() != null) {
            bean.setDateOfBirth(CommonJspUtils.displayValue(relation.getDob(), CommonJspUtils.STANDARD_DATE_FORMAT));
        }
        if (relation.getStartDate() != null) {
            bean.setEffectiveDate(CommonJspUtils.displayValue(relation.getStartDate(), CommonJspUtils.STANDARD_DATE_FORMAT));
        }
        if (relation.getEndDate() != null) {
            bean.setInactiveDate(CommonJspUtils.displayValue(relation.getEndDate(), CommonJspUtils.STANDARD_DATE_FORMAT));
        }
    }

    private void convertNames(Relation relation, RelationFinancialInfoBean bean) {
        Name name = relation.getName();
        if (name != null) {
            bean.setFirstName(name.getGivenName());
            bean.setLastName(name.getFamilyName());
            bean.setMiddleName(name.getMiddleName());
            bean.setPrefix(name.getPrefix());
            bean.setSuffix(name.getSuffix());
        }
    }

    private void convertSsns(Relation relation, RelationFinancialInfoBean bean) {
        SSN ssn = relation.getOfficialSsn();
        if (ssn != null) {
            bean.setSsn(CommonJspUtils.displaySSN(ssn.getSsnText()));
            if (ssn.getSsaMessage() != null)
                bean.setSsaMessage(ssn.getSsaMessage().getDescription());
            bean.setSsaVerificationDate(CommonDateUtils.format(ssn.getSsaVerificationDate(),
                    CommonDateUtils.MMDDYYYYHHMMSS));
            if (ssn.getSsaVerificationStatus() != null)
                bean.setSsaVerificationStatus(ssn.getSsaVerificationStatus().getCode());
            if (ssn.getSourceOfChange() != null)
                bean.setSsnSourceOfChange(ssn.getSourceOfChange().getCode());
        }

        SSN pssn = relation.getPseudoSsn();
        if (pssn != null) {
            bean.setPseudoSsn(CommonJspUtils.displaySSN(pssn.getSsnText()));
            if (pssn.getPseudoSSNReason() != null)
                bean.setPseudoSsnReason(pssn.getPseudoSSNReason().getCode());
        }

        // set the displaySSN
        if (bean.getSsn() != null && StringUtils.isNotEmpty(bean.getSsn()))
            bean.setDisplaySSN(bean.getSsn());
        else
            bean.setDisplaySSN(bean.getPseudoSsn());
    }

    private void convertRelationship(Relation relation, RelationFinancialInfoBean bean) {
        if (relation.getRelationship() != null) {
            bean.setRelationshipCode(relation.getRelationship().getCode());
            bean.setRelationship(relation.getRelationship().getDescription());
        }
    }

    private void convertGender(Relation relation, RelationFinancialInfoBean bean) {
        if (relation.getGender() != null) {
            bean.setGenderCode(relation.getGender().getCode());
            bean.setGender(relation.getGender().getDescription());
        }
    }

}
