/* ApplyFilter.java

{{IS_NOTE
	Purpose:
		
	Description:
		
	History:
		2013/8/5 , Created by dennis
}}IS_NOTE

Copyright (C) 2013 Potix Corporation. All Rights Reserved.

{{IS_RIGHT
}}IS_RIGHT
*/
package org.zkoss.zssex.ui.impl.ua;

import org.zkoss.util.resource.Labels;
import org.zkoss.zss.api.Range;
import org.zkoss.zss.api.Ranges;
import org.zkoss.zss.api.AreaRef;
import org.zkoss.zss.api.SheetOperationUtil;
import org.zkoss.zss.api.model.Book;
import org.zkoss.zss.api.model.Sheet;
import org.zkoss.zss.api.model.Book.BookType;
import org.zkoss.zss.model.STable;
import org.zkoss.zss.model.impl.AbstractSheetAdv;
import org.zkoss.zss.ui.UserActionContext;
import org.zkoss.zss.ui.impl.ua.AbstractProtectedHandler;
/**
 * 
 * @author dennis
 *
 */
public class CleanFilterHandler extends AbstractProtectedHandler {
	private static final long serialVersionUID = -7576345518460858743L;

	@Override
	public boolean isEnabled(Book book, Sheet sheet) {
		return book!=null && sheet!=null && !sheet.isProtected() && book.getType()!=BookType.XLS;
	}
	
	@Override
	protected boolean processAction(UserActionContext ctx) {
		Sheet sheet = ctx.getSheet();
		AreaRef selection = ctx.getSelection();
		Range range = Ranges.range(sheet, selection);
		//ZSS-988
		STable table = ((AbstractSheetAdv)sheet.getInternalSheet()).getTableByRowCol(range.getRow(), range.getColumn());
		if (table != null) {
			if (table.getAutoFilter() == null) {
				showInfoMessage(Labels.getLabel("zssex.actionhandler.msg.cant_clear_filter"));
				return true;
			}
		} else {
			// ZSS-246: check range available before "enabling" auto filter
			if(!range.isAutoFilterEnabled()) {
				final Range filterRange = range.findAutoFilterRange();
				if (filterRange == null) { 
					showInfoMessage(Labels.getLabel("zssex.actionhandler.msg.cant_find_filter_range"));
					return true;
				}
			}
		}
			
		SheetOperationUtil.resetAutoFilter(range);
		ctx.clearClipboard();
		return true;
	}

}
