/********************************************************************
 * Copyright © 2006 VHA. All rights reserved
 ********************************************************************/


package gov.va.med.esr.common.builder.entity;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import gov.va.med.esr.common.model.ee.Eligibility;
import gov.va.med.esr.common.model.ee.EnrollmentDetermination;
import gov.va.med.esr.common.model.ee.MilitaryService;
import gov.va.med.esr.common.model.ee.MilitaryServiceEpisode;
import gov.va.med.esr.common.model.ee.MilitaryServiceSiteRecord;
import gov.va.med.esr.common.model.ee.ServiceConnectionAward;
import gov.va.med.esr.common.model.financials.DependentFinancials;
import gov.va.med.esr.common.model.financials.FinancialStatement;
import gov.va.med.esr.common.model.lookup.Indicator;
import gov.va.med.esr.common.model.lookup.Relationship;
import gov.va.med.esr.common.model.person.DeathRecord;
import gov.va.med.esr.common.model.person.Dependent;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.service.external.person.EligibilitySummary;

/**
 * Initial javadoc for class EligibilitySummaryBuilder.
 * TODO - Add content here
 * 
 * Created Dec 18, 2006 11:41:03 AM
 * @author DNS   BOHMEG
 */
public class EligibilitySummaryBuilder extends EntityBuilder {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4424086576836580427L;

	public EligibilitySummary build(Person person) {
		/*
		 * IMPORTANT: This implementation is solely driven off of derived requirements and SOA request for ESR.
		 * The below set of data is not arbitrary and satisfies client requirements (eg, PSIM, IMDQ)
		 */
		
		EligibilitySummary eeSummary = new EligibilitySummary();
		Iterator itr = null;
		eeSummary.setClaimFolderNumber(person.getClaimFolderNumber());
		
		EnrollmentDetermination ed = person.getEnrollmentDetermination();
		if(ed != null) {
			eeSummary.setEligibilityLastModifiedBy(ed.getModifiedBy().getName());
			Eligibility primaryElig = ed.getPrimaryEligibility();
			if(primaryElig != null && primaryElig.getType() != null)
				eeSummary.setPrimaryEligibilityCode(primaryElig.getType().getCode());
		}
		
		DeathRecord dod = person.getDeathRecord();
		if(dod != null) {
			eeSummary.setDateOfDeathReportingStationNumber(dod.getFacilityReceived() != null ?
					dod.getFacilityReceived().getStationNumber() : null);
			eeSummary.setDateOfDeathSourceOfNotificationCode(dod.getDataSource() != null ? 
					dod.getDataSource().getCode() : null);
			eeSummary.setDateOfDeathLastModifiedDate(dod.getDeathLastModified() != null ?
					dod.getDeathLastModified().toString() : null);
		}
		
		ServiceConnectionAward sca = person.getServiceConnectionAward();
		if(sca != null) {
			eeSummary.setServiceConnected(sca.getServiceConnectedIndicator());
			eeSummary.setServiceConnectedPercentage(sca.getServiceConnectedPercentage());			
		}
		
		if(person.getPrisonerOfWar() != null) {
			Indicator powIndicator = person.getPrisonerOfWar().getPowIndicator();
			eeSummary.setPOWStatusIndicated(powIndicator != null ? powIndicator.toBoolean() : null);
		}
		
		MilitaryService ms = person.getMilitaryService();
		if(ms != null) {
			Set siteRecords = ms.getMilitaryServiceSiteRecords();
			itr = siteRecords != null ? siteRecords.iterator() : null;
			MilitaryServiceSiteRecord latestSiteRec = null;
			MilitaryServiceSiteRecord siteRec = null;
			// take the "latest" site data ESR has on file
			while(itr != null && itr.hasNext()) {
				siteRec = (MilitaryServiceSiteRecord) itr.next();
				if(latestSiteRec == null) {
					latestSiteRec = siteRec;
				} else {
					if(latestSiteRec.getCreatedOn().before(siteRec.getCreatedOn()))
						latestSiteRec = siteRec;
				}
			}
			if(latestSiteRec != null) {
				eeSummary.setPeriodOfServiceCode(latestSiteRec.getServicePeriod() != null ?
						latestSiteRec.getServicePeriod().getCode() : null);
				
				Set episodes = latestSiteRec.getMilitaryServiceEpisodes();
				itr = episodes != null ? episodes.iterator() : null;
				MilitaryServiceEpisode latestEpisode = null;
				MilitaryServiceEpisode episode = null;
				// take the "latest" episode for this guy
				while(itr != null && itr.hasNext()) {
					episode = (MilitaryServiceEpisode) itr.next();
					if(latestEpisode == null) {
						latestEpisode = episode;
					} else {
						if(latestEpisode.getEndDate() != null && latestEpisode.getEndDate().compareTo(episode.getEndDate()) < 0)
							latestEpisode = episode;
					}
				}
				if(latestEpisode != null) {
					eeSummary.setLastServiceBranchCode(latestEpisode.getServiceBranch() != null ?
							latestEpisode.getServiceBranch().getCode() : null);
					eeSummary.setLastServiceNumber(latestEpisode.getServiceNumber());
					eeSummary.setLastServiceEntryDate(latestEpisode.getStartDate() != null ?
							latestEpisode.getStartDate().toStandardFormat() : null);
					eeSummary.setLastServiceSeparationDate(latestEpisode.getEndDate() != null ?
							latestEpisode.getEndDate().toStandardFormat() : null);					
				}
			}
		}
		
		// see if we have a mother/father on file as legal dependents for latest years financial statements
		Map stmts = person.getFinancialStatements();
		if(stmts != null && !stmts.isEmpty()) {
			itr = stmts != null ? stmts.keySet().iterator() : null;
			Integer incomeYear = null;
			FinancialStatement fs = null;		
			Integer latestIncomeYear = null;
			while(itr != null && itr.hasNext()) {
				incomeYear = (Integer) itr.next();
				if(latestIncomeYear == null) {
					latestIncomeYear = incomeYear;
				} else {
					if(incomeYear.intValue() > latestIncomeYear.intValue())					
						latestIncomeYear = incomeYear;
				}
			}
			fs = person.getFinancialStatement(latestIncomeYear);
			// now loop through the dependent data and see what we got
			Set set = fs.getDependentFinancials();
			itr = set != null ? set.iterator() : null;
			DependentFinancials df = null;
			Dependent dep = null;
			if(itr != null && itr.hasNext()) {
				df = (DependentFinancials) itr.next();
				dep = df.getReportedOn();
				if(dep != null && dep.getRelationship() != null) {
					if(Relationship.CODE_FATHER.getCode().equals(dep.getRelationship().getCode()))
						eeSummary.setFathersName(dep.getName().getFormattedName());
					else if(Relationship.CODE_MOTHER.getCode().equals(dep.getRelationship().getCode()))
						eeSummary.setMothersName(dep.getName().getFormattedName());					
				}
			}			
		}		
		return eeSummary;		
	}
}
