package gov.va.med.esr.service.external;

import gov.va.med.esr.common.model.ee.EligibilityVerification;
import gov.va.med.esr.common.model.ee.FeeBasis;
import gov.va.med.esr.common.model.ee.IncompetenceRuling;
import gov.va.med.esr.common.model.ee.MECPeriod;
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.SpinalCordInjury;
import gov.va.med.esr.common.model.lookup.Indicator;
import gov.va.med.esr.common.model.person.BirthRecord;
import gov.va.med.esr.common.model.person.DeathRecord;
import gov.va.med.esr.common.model.person.Name;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.PreferredFacility;
import gov.va.med.esr.common.model.person.PreferredFacilityLite;
import gov.va.med.esr.common.persistent.person.MECPeriodDAO;
import gov.va.med.esr.service.IRSTransmissionService;
import gov.va.med.esr.service.PersonHelperService;
import gov.va.med.esr.service.PersonIdentityTraits;
import gov.va.med.esr.service.PreferredFacilityService;
import gov.va.med.esr.service.external.person.AssociationInfo;
import gov.va.med.esr.service.external.person.DeathRecondInfo;

import gov.va.med.esr.service.external.person.DemographicInfo;
import gov.va.med.esr.service.external.person.EESummary;
import gov.va.med.esr.service.external.person.EligibilityStatusInfo;
import gov.va.med.esr.service.external.person.EligibilityVerificationInfo;
import gov.va.med.esr.service.external.person.ExternalPerson;
import gov.va.med.esr.service.external.person.FeeBasisInfo;
import gov.va.med.esr.service.external.person.IVMCandidateInfo;
import gov.va.med.esr.service.external.person.IvmLetterCandidateInfo;
import gov.va.med.esr.service.external.person.IVMSummary;
import gov.va.med.esr.service.external.person.IncompetenceRulingInfo;
import gov.va.med.esr.service.external.person.InsuranceInfo;
import gov.va.med.esr.service.external.person.IVMLetterInfo;
import gov.va.med.esr.service.external.person.MSSummary;
import gov.va.med.esr.service.external.person.PIIData;
import gov.va.med.esr.service.external.person.PreferredFacilityInfo;
import gov.va.med.esr.service.external.person.RelationInfo;
import gov.va.med.esr.service.external.person.SendIVMInfo;
import gov.va.med.esr.service.external.person.SpinalCordInjuryInfo;
import gov.va.med.esr.service.external.person.collections.AssociationCollection;
import gov.va.med.esr.service.external.person.collections.FeeBasisCollection;
import gov.va.med.esr.service.external.person.collections.IVMCandidateCollection;
import gov.va.med.esr.service.external.person.collections.IVMLetterCandidateCollection;
import gov.va.med.esr.service.external.person.collections.InsuranceCollection;
import gov.va.med.esr.service.external.person.collections.PreferredFacilityCollection;
import gov.va.med.esr.service.external.person.collections.RelationCollection;
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.util.DateUtils;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ExternalSummaryFactoryImpl extends AbstractComponent implements ExternalSummaryFactory {


	private PersonHelperService personHelperService = null;

	private FinancialsSummaryFactory financialsSummaryFactory = null;

	private DemographicSummaryFactory demographicSummaryFactory = null;

	private MilitaryServiceFactory militaryServiceFactory;

	private ServiceConnectionAwardFactory serviceConnectionAwardFactory;

	private EnrollmentDeterminationFactory enrollmentDeterminationFactory;

	private PreferredFacilityService preferredFacilityService = null;

	private IVMSummaryFactory ivmSummaryFactory = null;

	public static final String IVMDATA = "IVMDATA";

	private MECPeriodDAO mecPeriodDAO = null;

	private IRSTransmissionService irsTransmissionService = null;



	public PersonHelperService getPersonHelperService() {
		return personHelperService;
	}

	public void setPersonHelperService(PersonHelperService personHelperService) {
		this.personHelperService = personHelperService;
	}


	public FinancialsSummaryFactory getFinancialsSummaryFactory() {
		return financialsSummaryFactory;
	}

	public void setFinancialsSummaryFactory(
			FinancialsSummaryFactory financialsSummaryFactory) {
		this.financialsSummaryFactory = financialsSummaryFactory;
	}

	public DemographicSummaryFactory getDemographicSummaryFactory() {
		return demographicSummaryFactory;
	}

	public void setDemographicSummaryFactory(
			DemographicSummaryFactory demographicSummaryFactory) {
		this.demographicSummaryFactory = demographicSummaryFactory;
	}

	public MilitaryServiceFactory getMilitaryServiceFactory() {
		return militaryServiceFactory;
	}

	public void setMilitaryServiceFactory(
			MilitaryServiceFactory militaryServiceFactory) {
		this.militaryServiceFactory = militaryServiceFactory;
	}

	public ServiceConnectionAwardFactory getServiceConnectionAwardFactory() {
		return serviceConnectionAwardFactory;
	}

	public void setServiceConnectionAwardFactory(
			ServiceConnectionAwardFactory serviceConnectionAwardFactory) {
		this.serviceConnectionAwardFactory = serviceConnectionAwardFactory;
	}

	public EnrollmentDeterminationFactory getEnrollmentDeterminationFactory() {
		return enrollmentDeterminationFactory;
	}

	public void setEnrollmentDeterminationFactory(
			EnrollmentDeterminationFactory enrollmentDeterminationFactory) {
		this.enrollmentDeterminationFactory = enrollmentDeterminationFactory;
	}

	private  PIIData extractPII(Person person) {
		PIIData pii = new PIIData();
		Boolean veteranInd = person.isVeteran();
		if (veteranInd == null) {
			veteranInd = new Boolean(false);
		}
		PersonIdentityTraits traits = person.getIdentityTraits();
		pii.setVpid(traits.getVpid() != null ? traits.getVpid()
				.getKeyValueAsString() : null);
		Name legalName = traits.getLegalName();
		if (legalName != null) {
			pii.setFirstName(legalName.getGivenName());
			pii.setLastName(legalName.getFamilyName());
			pii.setMiddleName(legalName.getMiddleName());
		}
		BirthRecord birthRec = traits.getBirthRecord();
		if (birthRec != null) {
			pii.setDob(birthRec.getBirthDate() != null ? birthRec
					.getBirthDate().toStandardFormat() : null);
		}
		pii.setGender(traits.getGender() != null ? traits.getGender().getDescription()
				: null);
		pii.setMaskedSsn(traits.getSsnText());

		return pii;
	}

	protected  void applyCommonData(Person person, ExternalPerson result) {
		Boolean veteranInd = person.isVeteran();
		if (veteranInd == null) {
			veteranInd = new Boolean(false);
		}
		result.setVeteran(veteranInd);
		result.setPiiData(extractPII(person));
	}



	public   EESummary buildEESummary(Person person, Integer incomeYear, String requestor) throws ServiceException{
		if (person == null)
			return null;

		EESummary eeSummary = new EESummary();

		applyEligibilityVerificationInfo(person,eeSummary);
		demographicSummaryFactory.applyDemographicsInfo(person, eeSummary);
		enrollmentDeterminationFactory.applyEnrollmentDeterminationInfo(person, eeSummary);
		getFinancialsSummaryFactory().applyFinancialsInfo(person, eeSummary, incomeYear, requestor);
		eeSummary.setMilitaryServiceInfo(militaryServiceFactory.getMilitaryServiceInfo(person));
		applyIncompetenceRulingInfo( person,eeSummary);
		applyDeathRecord( person, eeSummary);
		eeSummary.setPrisonerOfWarInfo(militaryServiceFactory.getPOWInfo(person));
		eeSummary.setPurpleHeart(militaryServiceFactory.getPurpleHeartInfo(person));
		applySpinalCardInjury(person,eeSummary);


		AssociationInfo[] associations = demographicSummaryFactory.buildContacts(person);

		if ( associations != null)
		{
			eeSummary.setAssociations(new AssociationCollection(associations));
		}


		/**
		 * OTHER relations like FATHER, MOTHER ETC
		 */
		RelationInfo[] relations = demographicSummaryFactory.buildRelations(person);
		if ( relations != null && relations.length > 0)
		{
			eeSummary.setRelations(new RelationCollection(relations));
		}

		eeSummary.setEmploymentInfo(demographicSummaryFactory.buildEmployment(person));

		applyFeeBasis(person, eeSummary);

		InsuranceInfo[] insurances = demographicSummaryFactory.buildInsurance(person);
		if ( insurances != null && insurances.length > 0 )
		{
			eeSummary.setInsuranceList(new InsuranceCollection(insurances));
		}
		// CCR11424 -Enhance the payload delivered by E/E web services to include multiple Preferred Facilities
		if (person.getMostRecentPreferredFacility()!=null){
			applyPreferredFacilities(person,eeSummary);
		}

		//applying IVM specific data
		//removed as per CCR 12665
		//Set sites = getFinancialsSummaryFactory().getVisitedSites(person);
		//Making MVI calls to be accessible only for IVM requests
		//if(requestor.equalsIgnoreCase(IVMDATA)){
			eeSummary.setPersonInfo(ivmSummaryFactory.applyPersonInfo(person, requestor));
		//}

		eeSummary.setConsentInfo(getFinancialsSummaryFactory().applyConsentInfo(person, incomeYear));


		return eeSummary;
	}


    public   EESummary buildEDStatus(Person person) {
        EESummary eeSummary = new EESummary();
        if (person == null){
            EligibilityStatusInfo info = new EligibilityStatusInfo();
            info.setEligibilityStatus("Not Found");
            eeSummary.setEligibilityStatusInfo(info);
            return eeSummary;
        }

        enrollmentDeterminationFactory.applyEligibilityStatusInfo(person, eeSummary);
        return eeSummary;
    }



    public   void buildEESummaryHistory(Person person, EESummary eeSummary, String categoryName, Date acaStart, Date acaEnd) {
        if (person == null)
            return;
        if(categoryName.equals("ELIGIBILITY")){

        applyEligibilityVerificationInfo(person,eeSummary);
       // enrollmentDeterminationFactory.applyEligibilityInfo(person, eeSummary);
        }
        if(categoryName.equals("ENROLLMENT")){
            enrollmentDeterminationFactory.applyEnrollmentInfo(person, eeSummary);
        }
        if(categoryName.equals("PRIMARYELIGIBILITY")){
            enrollmentDeterminationFactory.applyEligibilityInfo(person, eeSummary);
        }
        if(categoryName.equals("DISABILITY")){
            enrollmentDeterminationFactory.applyDisabilityInfo(person, eeSummary);
        }
        if(categoryName.equals("INSURANCE")){
            InsuranceInfo[] insurances = demographicSummaryFactory.buildInsurance(person);
            if ( insurances != null && insurances.length > 0 )
            {
                eeSummary.setInsuranceList(new InsuranceCollection(insurances));
            }
        }

        //WI 324899 MEC Period ACA coverage period by date
        if(categoryName.equals("ACA_MEC")){
        	boolean covered = false;
        	MECPeriod period = null;


        	try {
        		Calendar cal = Calendar.getInstance();
        		if (acaStart != null) {
        			cal.setTime(acaStart);
        		} else {
        			cal.setTime(acaEnd);
        		}

        		int calYear = cal.get(Calendar.YEAR);


	   			period = this.getIrsTransmissionService().
		   				combineAllPeriods((BigDecimal)person.getPersonEntityKey().getKeyValue());

		   		if (acaStart == null) acaStart = acaEnd;
		   		if (acaEnd == null) acaEnd = acaStart;

		   		if (period != null && period.getMecStartDate() != null && period.getMecStartDate().before(acaEnd) &&
		   				(period.getMecEndDate() == null || period.getMecEndDate().after(acaStart))) {

		   				covered = true;
		   		}

		   		List allPeriods = this.getIrsTransmissionService().getAllPeriods((BigDecimal)person.getPersonEntityKey().getKeyValue());

		   		boolean coveredForGap = false;

		   		if (allPeriods != null && allPeriods.size() > 1) {
		   			for (int i = 0; i < allPeriods.size(); i++) {
		   				MECPeriod p = (MECPeriod)allPeriods.get(i);

		   				if (p.getMecStartDate() != null && acaStart.after(p.getMecStartDate())) {
		   					if (p.getMecEndDate() != null) {
		   						if (acaStart.before(p.getMecEndDate())) {
		   							coveredForGap = true;
		   						}
		   					} else {
		   						coveredForGap = true;
		   					}
		   				} else { //start date before period start date
		   					if (acaEnd.after(p.getMecStartDate())) {
		   						if (p.getMecEndDate() != null) {
		   							if (acaEnd.before(p.getMecEndDate())) {
		   								coveredForGap = true;
		   							}
		   						} else {
		   							coveredForGap = true;
		   						}
		   					}
		   				}
		   			}

		   			if (covered && !coveredForGap) {
		   				covered = false;
		   			}
		   		}



        	} catch (Exception ex) {
        		logger.error("Unknown Error during ACA MEC Enrollment History", ex);
        		covered = false;
        	}


        	try {
        		enrollmentDeterminationFactory.applyMecInfo(person, eeSummary, covered, period, acaStart, acaEnd);
        	} catch (Exception ex) {
        		logger.error("Unknown Error during ACA MEC Enrollment History", ex);
        	}
        }


    }

	public  MSSummary buildMSSummary(Person person) {
		if (person == null)
			return null;

		MSSummary summary = new MSSummary();
		applyCommonData(person, summary);

		if (person.getPrisonerOfWar() != null) {
			Indicator powIndicator = person.getPrisonerOfWar()
					.getPowIndicator();
			summary.setPOWStatusIndicated(powIndicator != null ? powIndicator
					.toBoolean() : null);
		}

		MilitaryService ms = person.getMilitaryService();
		if (ms != null) {
			Set siteRecords = ms.getMilitaryServiceSiteRecords();
			Iterator 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) {
				summary
						.setPeriodOfServiceCode(latestSiteRec
								.getServicePeriod() != null ? latestSiteRec
								.getServicePeriod().getName() : 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) {
					summary.setLastServiceBranchCode(latestEpisode
							.getServiceBranch() != null ? latestEpisode
							.getServiceBranch().getDescription() : null);
					summary.setLastServiceNumber(latestEpisode
							.getServiceNumber());
					summary.setLastServiceEntryDate(latestEpisode
							.getStartDate() != null ? latestEpisode
							.getStartDate().toStandardFormat() : null);
					summary.setLastServiceSeparationDate(latestEpisode
							.getEndDate() != null ? latestEpisode.getEndDate()
							.toStandardFormat() : null);
				}
			}
		}
		return summary;
	}


	public IVMSummary buildIVMCandidates(Date date) {
		IVMSummary ivmCandidate = new IVMSummary();

		IVMCandidateInfo[] ivmCandidates = null;
		try {
			ivmCandidates = ivmSummaryFactory
					.buildIVMCandidatesInfo(date);
			if (ivmCandidates != null) {
				ivmCandidate.setIVMCandidates(new IVMCandidateCollection(
						ivmCandidates));
			}
		} catch (ServiceException e) {
			ivmCandidate.setStatus("Build IVM Candidate: " + date + "caused exception " + e);
		}

		return ivmCandidate;

	}

	public IVMSummary buildIvmLetterCandidates() {
		IVMSummary summary = new IVMSummary();

		IvmLetterCandidateInfo[] ivmLetterCandidates = null;
		try {
			ivmLetterCandidates = ivmSummaryFactory.buildIvmLetterCandidatesInfo();
			if (ivmLetterCandidates != null) {
				summary.setIvmLetterCandidates(new IVMLetterCandidateCollection(ivmLetterCandidates));
			}
		} catch (ServiceException e) {
			summary.setStatus("Build IVM Letter Candidate: caused exception " + e);
		}

		return summary;
	}

	public IVMSummary updateIvmStatus(BigDecimal transactionId, String status){
		IVMSummary ivmSummary = new IVMSummary();
		try {
			if(ivmSummaryFactory.updateIVMStatus(transactionId, status)){
				ivmSummary.setAcknowledgement("Request Received and IVM status is updated");
			}
			else{
				ivmSummary.setStatus("Update IVM Status: Could not find record using transaction id "+ transactionId);
			}

		} catch (ServiceException e) {
			ivmSummary.setStatus("Update IVM Status: "+ transactionId + " caused exception " + e);
			return ivmSummary;
		}
		return ivmSummary;
	}

	public  IVMSummary processIVMIncomeTest(Person person, Integer incomeYear, SendIVMInfo incomingIvmObj,
			IVMLetterInfo incomingLetterObj){
		IVMSummary ivmSummary = new IVMSummary();
		ivmSummaryFactory.processIVMIncomeTest(person, incomeYear, incomingIvmObj, ivmSummary, incomingLetterObj);

		return ivmSummary;

	}

	private  void applyEligibilityVerificationInfo(Person person,
			EESummary summary) {
		EligibilityVerification ev = person.getEligibilityVerification();
		if (ev == null)
			return;

		EligibilityVerificationInfo evInfo = new EligibilityVerificationInfo();
		evInfo.setVerificationMethod(ev.getVerificationMethod());

		if (ev.getEligibilityStatus() != null)
			evInfo.setEligibilityStatus(ev.getEligibilityStatus().getDescription());

		if (ev.getEligibilityStatusDate() != null)
			evInfo.setEligibilityStatusDate(ev.getEligibilityStatusDate()
					.getStandardFormat());


		summary.setEligibilityVerificationInfo(evInfo);
	}





	private  void applyDeathRecord(Person person, EESummary eeSummary)
	{
		DeathRecord dr = person.getDeathRecord();
		if ( dr == null) return;

		DeathRecondInfo drInfo = new DeathRecondInfo();
		drInfo.setDataSource(dr.getDataSource() != null ? dr.getDataSource().getDescription():null);
		drInfo.setDeathDate(dr.getDeathDate() != null ? dr.getDeathDate().getStandardFormat():null);
		drInfo.setDeathLastModified(dr.getDeathLastModified());
		drInfo.setDeathReportDate(dr.getDeathReportDate());
		drInfo.setFacilityReceived(dr.getFacilityReceived() != null ? dr.getFacilityReceived().getSiteNumberAndName():null);
		//drInfo.setLazarusDate(dr.getLazarusDate() != null ? dr.getLazarusDate().getStandardFormat():null);

		eeSummary.setDeathRecond(drInfo);

	}



	private  void applyIncompetenceRulingInfo(Person person, EESummary eeSummary)
	{
		IncompetenceRuling ruling = person.getIncompetenceRuling();
		if ( ruling == null) return;

		IncompetenceRulingInfo rulingInfo = new IncompetenceRulingInfo();
		rulingInfo.setCivilRulingDate(ruling.getCivilRulingDate() != null? ruling.getCivilRulingDate().getStandardFormat():null);
		rulingInfo.setVaRulingDate(ruling.getVaRulingDate() != null? ruling.getVaRulingDate().getStandardFormat():null);
		rulingInfo.setIncompetent(ruling.getIncompetent());
		eeSummary.setIncompetenceRulingInfo(rulingInfo);
	}

	private  void applyFeeBasis(Person person, EESummary summary) {

		Set feeBaseSet = person.getFeeBasis();
		if (feeBaseSet != null && feeBaseSet.size() > 0) {
			Iterator itr = feeBaseSet != null ? feeBaseSet.iterator() : null;
			int count = 0;
			FeeBasisInfo[] feeBasisInfoArray = new FeeBasisInfo[feeBaseSet
					.size()];
			while (itr != null && itr.hasNext()) {

				FeeBasis feeBasis = (FeeBasis) itr.next();
				if (feeBasis != null) {
					FeeBasisInfo feeBasisInfo = new FeeBasisInfo();
					feeBasisInfo.setAuthorizationFromDate(feeBasis
							.getAuthorizationFromDate());
					feeBasisInfo.setAuthorizationToDate(feeBasis
							.getAuthorizationToDate());
					feeBasisInfo.setReportDate(feeBasis.getReportDate());
					feeBasisInfo
							.setReportSite(feeBasis.getReportSite() != null ? feeBasis
									.getReportSite().getSiteNumberAndName()
									: null);
					feeBasisInfo
							.setTreatmentType(feeBasis.getTreatmentType() != null ? feeBasis
									.getTreatmentType().getDescription()
									: null);
					feeBasisInfo
							.setProgram(feeBasis.getProgram() != null ? feeBasis
									.getProgram().getDescription()
									: null);
					feeBasisInfoArray[count] = feeBasisInfo;
					count++;
				}
			}
			if ( feeBasisInfoArray != null && feeBasisInfoArray.length > 0 )
			{
				summary.setFeeBasisList(new FeeBasisCollection(feeBasisInfoArray));
			}
		}

	}


	private  void applySpinalCardInjury(Person person, EESummary summary) {
		SpinalCordInjury sc = (SpinalCordInjury) enrollmentDeterminationFactory.getClinicalDetermination(SpinalCordInjury.class, person);

		if (sc == null)
			return ;

		SpinalCordInjuryInfo scInfo = new SpinalCordInjuryInfo();
		scInfo
				.setDeterminationFacility(sc.getDeterminationFacility() != null ? sc
						.getDeterminationFacility().getSiteNumberAndName()
						: null);
		scInfo
				.setSpinalCordInjuryType(sc.getSpinalCordInjuryType() != null ? sc
						.getSpinalCordInjuryType().getDescription()
						: null);
		summary.setSpinalCordInjuryInfo(scInfo);
		return;
	}

private void applyPreferredFacilities(Person person,EESummary summary){

	Set pfList = person.getPreferredFacilities();
    Set activePfs = this.getActivePreferredFacilities(pfList);

   	DemographicInfo demographicInfo = summary.getDemographics();
   //	Set<VAFacility> pfSites = new HashSet<VAFacility>();
   	PreferredFacilityInfo[] pfInfos;
   	PreferredFacility pf;
   	int i=0;
   	if (!activePfs.isEmpty()) {
   		pfInfos = new PreferredFacilityInfo[activePfs.size()];

   		for (Iterator iter = activePfs.iterator(); iter.hasNext(); ) {
   			pf = (PreferredFacility)iter.next();
   			pfInfos[i]= new PreferredFacilityInfo();
   			pfInfos[i].setPreferredFacility(pf.getFacility().getSiteNumberAndName());
   			if(pf.getAssignmentDate() != null){
   			pfInfos[i].setAssignmentDate(pf.getAssignmentDate());
   			}
   			if(pf.getUnassignmentDate() != null){
   			pfInfos[i].setUnassignmentDate(pf.getUnassignmentDate());
   			}
   			i++;
   		}
   	} else {
   		// no active PFs found, return just the most recent (inactive) PF
   		pfInfos = new PreferredFacilityInfo[1];
   		pf = (PreferredFacility) this.getPreferredFacilityService().getMostRecentPreferredFacility(person);
   		if (pf != null) {
   			pfInfos[0]= new PreferredFacilityInfo();
   			pfInfos[0].setPreferredFacility(pf.getFacility().getSiteNumberAndName());
   			if(pf.getAssignmentDate() != null){
   			pfInfos[0].setAssignmentDate(pf.getAssignmentDate());
   			}
   			if(pf.getUnassignmentDate() != null){
   			pfInfos[0].setUnassignmentDate(pf.getUnassignmentDate());
   			}
   		}
   		else{
   			pfInfos[0]= new PreferredFacilityInfo();
   			pfInfos[0].setPreferredFacility(null);
   		}
   	}
   		if ( pfInfos != null && pfInfos.length > 0 )
		{
			demographicInfo.setPreferredFacilities(new PreferredFacilityCollection(pfInfos));
		}

	    summary.setDemographics(demographicInfo);
 }


/**
 * Returns regular object used only for general processing.
 *
 * @param pfList
 * @return
 * @throws ServiceException
 */
private Set getActivePreferredFacilities(Set pfList) {
	Set activePfs = new HashSet();
	PreferredFacility pf = null;

	for (Iterator iter = pfList.iterator(); iter.hasNext(); ) {
		pf = (PreferredFacility)iter.next();
		if (isPFActive(pf)) {
			activePfs.add(pf);
		}
	}
	return activePfs;
}
/**
 * Checks if a preferred facility is active.
 * Returns true if pf has unassignment date being null or future dated.
 * @param pf
 * @return
 */
private boolean isPFActive(PreferredFacilityLite pf) {

	Date currentDate = DateUtils.getCurrentDateTime();
	return ((pf.getUnassignmentDate() == null || pf.getUnassignmentDate().after(currentDate)));
}

public PreferredFacilityService getPreferredFacilityService() {
	return preferredFacilityService;
}

public void setPreferredFacilityService(
		PreferredFacilityService preferredFacilityService) {
	this.preferredFacilityService = preferredFacilityService;
}

public IVMSummaryFactory getIvmSummaryFactory() {
	return ivmSummaryFactory;
}

public void setIvmSummaryFactory(IVMSummaryFactory ivmSummaryFactory) {
	this.ivmSummaryFactory = ivmSummaryFactory;
}

public MECPeriodDAO getMecPeriodDAO() {
	return mecPeriodDAO;
}

public void setMecPeriodDAO(MECPeriodDAO mecPeriodDAO) {
	this.mecPeriodDAO = mecPeriodDAO;
}

public IRSTransmissionService getIrsTransmissionService() {
	return irsTransmissionService;
}

public void setIrsTransmissionService(
		IRSTransmissionService irsTransmissionService) {
	this.irsTransmissionService = irsTransmissionService;
}

}
