package de.proveo.rts.web.portlet.tags;

import java.io.IOException;

import javax.faces.component.UIComponent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.facelets.FaceletContext;
import com.sun.facelets.tag.TagAttribute;
import com.sun.facelets.tag.TagConfig;
import com.sun.facelets.tag.TagHandler;

import de.proveo.rts.web.controller.SessionController;

/**
 * Maps value binding and type so other tags can access it.
 */
public final class SetDataTableSortingHandler extends TagHandler
{
	private static final Log log = LogFactory.getLog(SetDataTableSortingHandler.class);

	private final TagAttribute dataTableId;
	private final TagAttribute columnName;
	private final TagAttribute ascending;

	/**
	 * Constructor. Set up the attributes for this tag.
	 * 
	 * @param config
	 *            TagConfig
	 */
	public SetDataTableSortingHandler(final TagConfig config)
	{
		super(config);
		this.dataTableId = this.getRequiredAttribute("dataTableId");
		this.ascending = this.getRequiredAttribute("ascending");
		this.columnName = this.getRequiredAttribute("columnName");

	}

	/**
	 * Apply.
	 * @param faceletsContext
	 *            faceletsContext
	 * @param parent
	 *            parent
	 * @throws IOException
	 *             IOException
	 */
	public void apply(final FaceletContext faceletsContext, final UIComponent parent)
	{
		Object value = columnName.getValueExpression(faceletsContext, Object.class).getValue(faceletsContext);
		
		if (value != null)
		{
			String tableId = dataTableId.getValue(faceletsContext);
			String columnId = columnName.getValue(faceletsContext);
			Boolean sortAscending = Boolean.parseBoolean(ascending.getValue(faceletsContext));
			//TODO: remove: SessionController.getSortBean().setSortForTable(tableId, columnId, sortAscending);
			SessionController.getSessionDataBean().getTableSessionData(tableId).getSortBean().setSortColumn(columnId, sortAscending);
		}

	}
}
