package org.richfaces.model.internal;

import java.util.Comparator;

import org.richfaces.model.SortField;

/**
 * Comparator for {@link JavaBeanWrapper} objects.
 * Compares them using {@link SortField} sequence.
 * 
 * @author Maksim Kaszynski
 *
 */
final class WrappedBeanComparator implements Comparator {
	/**
	 * 
	 */
	private final SortField[] fields;

	/**
	 * @param fields
	 */
	WrappedBeanComparator(SortField[] fields) {
		this.fields = fields;
	}

	public int compare(Object o1, Object o2) {
		
		int result = 0;
		JavaBeanWrapper w1 = (JavaBeanWrapper) o1;
		JavaBeanWrapper w2 = (JavaBeanWrapper) o2;
		
		for (int i = 0; i < fields.length && result == 0; i++) {
			
			String prop = fields[i].getName();
			Boolean asc = fields[i].getAscending();
			
			Object p1 = w1.getProperty(prop);
			Object p2 = w2.getProperty(prop);
			
			if (p1 instanceof Comparable) {
				result = ((Comparable) p1).compareTo(p2);
			}
			
			if (asc != null && !asc.booleanValue()) {
				result = -result;
			}
			
		}
		
		
		return result;
	}
}