// Package 
package gov.va.med.esr.ui.report.action;

// Java Classes
import java.util.List;
import java.util.Iterator;
import java.util.Comparator;
import java.util.Collections;

// Library Classes
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.collections.comparators.NullComparator;
import org.apache.commons.beanutils.BeanComparator;

// Framework Classes
import gov.va.med.fw.ui.valuelist.SearchValueListAdapter;
import gov.va.med.fw.util.SortElement;

// ESR Classes
import gov.va.med.esr.common.model.lookup.StandardReport;

/**
 * A custom value list adapter for the available reports.
 */
public class AvailableReportsValueListAdapter extends SearchValueListAdapter
{
    private static final long serialVersionUID = 5479718842749865481L;

    /**
     * Sorts the results list using the sort elements.
     *
     * @param results The results to sort
     * @param sortElements The sort elements
     */
    protected void performSort(List results, List sortElements)
    {
        if ((sortElements != null) && (sortElements.size() > 0) && (results != null) &&
            (results.size() > 0))
        {
            ComparatorChain chain = new ComparatorChain();
            for (Iterator iterator = sortElements.iterator(); iterator.hasNext();)
            {
                // Get the sort element and defined a default NullComparator
                SortElement sortElement = (SortElement)iterator.next();
                Comparator sortComparator = new NullComparator();

                // If sorting on the standardReport.code, add a custom comparator to handle
                // proper sorting on the alphabetic and numeric portions of the code.
                if ("code".equals(sortElement.getSortColumn()))
                {
                    sortComparator = StandardReport.getCodeComparator();
                }
                chain.addComparator(
                    new BeanComparator(sortElement.getSortColumn(), sortComparator),
                    sortElement.getSortDirection().equals(SortElement.DESCENDING));
            }
            Collections.sort(results, chain);
        }
    }
}
