package com.agilex.vamf.missionhealth.domain;

import java.util.Date;

import com.agilex.vamf.utils.StringUtil;

public class PatientSortingAlgorithm {
	public static final int EQUAL_TO = 0;
	public static final int GREATER_THAN = 1;
	public static final int LESS_THAN = -1;

	public int compare(Patient patientX, Patient patientY) {
		Date patientXDOB = null;
		Date patientYDOB = null; 
		
		if (patientX == null)
			throw new NullPointerException("Cannot compare null patient");
		if (patientY == null)
			throw new NullPointerException("Cannot compare patient to null");

		if (patientX.getDateOfBirth() != null){
			patientXDOB = patientX.getDateOfBirth().getDate();
		}
		
		if (patientY.getDateOfBirth() != null){
			patientYDOB = patientY.getDateOfBirth().getDate();
		}
		
		int result = compare(StringUtil.toLowerCaseIgnoreNull(patientX.getLastName()), StringUtil.toLowerCaseIgnoreNull(patientY.getLastName()));
		if (result == EQUAL_TO)
			result = compare(StringUtil.toLowerCaseIgnoreNull(patientX.getFirstName()), StringUtil.toLowerCaseIgnoreNull(patientY.getFirstName()));
		if (result == EQUAL_TO)
			result = compare(patientXDOB, patientYDOB);
		if (result == EQUAL_TO)
			result = compare(patientX.getSsn(), patientY.getSsn());

		return result;
	}

	private <T> int compare(Comparable<T> x, T y) {
		if ((x == null) && (y == null))
			return EQUAL_TO;
		else if ((x == null) && (y != null))
			return LESS_THAN;
		else if ((x != null) && (y == null))
			return GREATER_THAN;
		else
			return x.compareTo(y);
	}
}
