package de.proveo.rts.web.portlet.managedBeans.common.dataTable.myfaces;

import java.util.HashMap;

import javax.faces.event.ActionEvent;

import org.apache.myfaces.component.html.ext.HtmlDataTable;
import org.apache.myfaces.custom.column.HtmlSimpleColumn;
import org.apache.myfaces.custom.sortheader.HtmlCommandSortHeader;

import de.proveo.rts.web.util.RtsUtil;

public class MyFacesSessionDataBean
{
	private HashMap<String, MyFacesTableSortObject> tableSortMap = new HashMap<String, MyFacesTableSortObject>();
	
	public void sortListener(ActionEvent e)
	{
		HtmlCommandSortHeader sortHeader = (HtmlCommandSortHeader)e.getComponent();
		HtmlSimpleColumn column = (HtmlSimpleColumn) sortHeader.getParent();
		HtmlDataTable table = (HtmlDataTable)column.getParent();
		Boolean sortable = (Boolean)column.getAttributes().get("sortable");
		//isSortColumn only on standard columns 
		if(sortable)
			if(column.getAttributes().get("isSortColumn") != null)
				sortable = !(Boolean)column.getAttributes().get("isSortColumn");
		sortColumn(table.getId(), sortHeader.getColumnName(), sortable);
		RtsUtil.handleNavigation(RtsUtil.getViewName());
	}
	
	public void sortColumn(String tableId, String columnName, Boolean sortable)
	{
		MyFacesTableSortObject sortObject = tableSortMap.get(tableId);
		Boolean sortAscending = true;
		//Table has not been sorted yet:
		if(sortObject == null)
		{
			sortObject = new MyFacesTableSortObject();
			sortObject.setSortColumn(columnName);
			sortObject.setSortAscending(sortAscending);
			tableSortMap.put(tableId, sortObject);
			return;
		}
		
		//Important: dataTable attribute "sortAscending" uses Setter, so dont change 
		//sortAscending value here, it is automatically changed
		if(sortObject.getSortColumn().equals(columnName))
			sortAscending = (sortable ? sortObject.isSortAscending() : !sortObject.isSortAscending());
		sortObject.setSortColumn(columnName);
		sortObject.setSortAscending(sortAscending);
		tableSortMap.put(tableId, sortObject);
	}

	public void setSortColumn(String tableId, String columnName, Boolean sortAscending)
	{
		if(!tableSortMap.containsKey(tableId))
		{
			MyFacesTableSortObject sortObject = new MyFacesTableSortObject();
			sortObject.setSortColumn(columnName);
			sortObject.setSortAscending(sortAscending);
			tableSortMap.put(tableId, sortObject);
		}
	}
	
	public HashMap<String, MyFacesTableSortObject> getTableSortMap()
	{
		return tableSortMap;
	}
	
	public void setTableSortMap(HashMap<String, MyFacesTableSortObject> tableSortMap)
	{
		this.tableSortMap = tableSortMap;
	}
}
