/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
// Package
package gov.va.med.esr.common.util;

// Java classes
import java.util.Date;

// Library classes

// Framework classes
import gov.va.med.fw.util.DateComparator;

// ESR classes
import gov.va.med.esr.common.model.ee.MilitaryServiceEpisode;
import gov.va.med.esr.common.infra.ImpreciseDateUtils;

/**
 * Compares either the service entry date or separation date of 2 episodes 
 *
 * Project: Common</br>
 * Created on: 3:28:02 PM </br>
 *
 * @author DNS   LEV
 */
public class MilitaryServiceEpisodeComparator extends DateComparator {

	/**
	 * An instance of compareEndDate
	 */
	private boolean compareEndDate = true;
	
	/**
	 * A default constructor
	 */
	public MilitaryServiceEpisodeComparator( boolean compareEndDate ) {
		super();
		this.compareEndDate = compareEndDate;
	}

	/**
	 * A default constructor
	 */
	public MilitaryServiceEpisodeComparator() {
		this( true );
	}

	/**
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	 */
	public int compare( Object arg1, Object arg2 ) {
		// Return -1 for episode1 < episode2. 1 for episode1 > episode2. 0 for equality
		int equal = 0;
		if( arg1 instanceof MilitaryServiceEpisode && arg2 instanceof MilitaryServiceEpisode ) {
			MilitaryServiceEpisode episode1 = (MilitaryServiceEpisode)arg1;
			MilitaryServiceEpisode episode2 = (MilitaryServiceEpisode)arg2;
			
			Date episode1_date = null;
			Date episode2_date = null;
			
			if( compareEndDate ) {
				episode1_date = ImpreciseDateUtils.getDateWithDefault( episode1.getEndDate() ); 
				episode2_date = ImpreciseDateUtils.getDateWithDefault( episode2.getEndDate() ); 
			}
			else {
				episode1_date = ImpreciseDateUtils.getDateWithDefault( episode1.getStartDate() ); 
				episode2_date = ImpreciseDateUtils.getDateWithDefault( episode2.getStartDate() ); 
			}
            
            // Compare the 2 episodes for the most recent
            if( episode1_date != null && episode2_date != null ) {
                equal = super.compare( episode1_date, episode2_date );
            } else {
                if(episode1_date == null && episode2_date == null) {
                    equal = 0;
                } else if(episode1_date == null) {
                    equal = -1;
                } else {
                    equal = 1;
                }
            }
		}
		return equal;
	}
}
