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

import javax.faces.context.FacesContext;

import org.richfaces.component.Column;
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();
		int columnIndex = e.getSortColumn();
		Column column = 
			(Column) grid.getChildren().get(columnIndex);
		
		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, columnIndex, nextSortOrder(null, e.getSuggestedOrder()));
		
		if (fields != null) {
			for (int i = 0; i < fields.length; i++) {
				SortField sortField = fields[i];
				if (sortField.getIndex() == columnIndex || 
						(sortField.getName() != null && 
								name != null && 
								name.equals(sortField.getName()))) {
					
					Boolean asc = nextSortOrder(sortField.getAscending(), e.getSuggestedOrder()) ;
					
					newField = new SortField(name, columnIndex, asc);
					break;
					
				}
			}
		}
		
		sortOrder.setFields(new SortField[] {newField});
	}
	

}
