/**
 * 
 */
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 implements SortListener {

	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.getValueBinding("sortOrder") != null) {
				grid.getValueBinding("sortOrder").setValue(FacesContext.getCurrentInstance(), sortOrder);
			}
			
		}
		
		SortField[] fields = sortOrder.getFields();
		
		SortField newField = new SortField(name, columnIndex, Boolean.TRUE);
		
		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 = sortField.getAscending();
					asc = Boolean.TRUE.equals(asc) ? Boolean.FALSE : Boolean.TRUE;
					
					newField = new SortField(name, columnIndex, asc);
					break;
					
				}
			}
		}
		
		sortOrder.setFields(new SortField[] {newField});
	}
	

}
