/**
 * 
 */
package org.richfaces.event.sort;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.richfaces.component.UIScrollableDataTable;
import org.richfaces.component.util.ColumnUtil;
import org.richfaces.model.SortField;
import org.richfaces.model.SortOrder;

/**
 * @author Maksim Kaszynski
 *
 */
public class SingleColumnSortListener extends AbstractSortListener {

	public static final SingleColumnSortListener INSTANCE = new SingleColumnSortListener();
	
	private SingleColumnSortListener() {
	}
	
	/* (non-Javadoc)
	 * @see org.richfaces.event.sort.SortListener#processSort(org.richfaces.event.sort.SortEvent)
	 */
	public void processSort(SortEvent e) {
		UIScrollableDataTable grid = (UIScrollableDataTable) e.getComponent();
		String sortColumn = e.getSortColumn();

		UIComponent column = grid.findComponent(sortColumn);
		
		String name = ColumnUtil.getColumnSorting(column);
		
		SortOrder sortOrder = grid.getSortOrder();
		if (sortOrder == null) {
			sortOrder = new SortOrder();
			grid.setSortOrder(sortOrder);
			
			if (grid.getValueExpression("sortOrder") != null) {
				grid.getValueExpression("sortOrder").setValue(FacesContext.getCurrentInstance().getELContext(), sortOrder);
			}
			
		}
		
		SortField[] fields = sortOrder.getFields();
		
		SortField newField = new SortField(name, nextSortOrder(null, e.getSuggestedOrder()));
		
		if (fields != null) {
			for (int i = 0; i < fields.length; i++) {
				SortField sortField = fields[i];
				if (name != null && name.equals(sortField.getName())) {
					
					Boolean asc = nextSortOrder(sortField.getAscending(), e.getSuggestedOrder()) ;
					
					newField = new SortField(name, asc);
					break;
					
				}
			}
		}
		
		sortOrder.setFields(new SortField[] {newField});
	}
	

}
