/* CustomFiltersHandler.java

{{IS_NOTE
	Purpose:
		
	Description:
		
	History:
		2016/05/13 , Created by Henri
}}IS_NOTE

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

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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.SerializableEventListener;
import org.zkoss.zss.api.AreaRef;
import org.zkoss.zss.api.Ranges;
import org.zkoss.zss.api.Range.AutoFilterOperation;
import org.zkoss.zss.api.Range.SheetVisible;
import org.zkoss.zss.api.model.Book;
import org.zkoss.zss.api.model.Sheet;
import org.zkoss.zss.model.SAutoFilter;
import org.zkoss.zss.model.SAutoFilter.NFilterColumn;
import org.zkoss.zss.model.SCustomFilter;
import org.zkoss.zss.model.SCustomFilters;
import org.zkoss.zss.ui.UserActionContext;
import org.zkoss.zss.ui.impl.ua.AbstractBookHandler;
import org.zkoss.zssex.ui.dialog.Top10FilterCtrl;
import org.zkoss.zssex.ui.dialog.UnhideSheetCtrl;
import org.zkoss.zssex.ui.dialog.impl.DialogCallbackEvent;
import org.zkoss.zul.Messagebox;

/**
 * @author Henri
 * @since 3.9.0
 */
public class Top10FilterHandler extends AbstractBookHandler{
	private static final long serialVersionUID = 2741108880166709295L;

	@Override
	protected boolean processAction(final UserActionContext ctx) {
		final Sheet sheet = ctx.getSheet();
		
		//TODO: check if a table filter by check ref
		final SAutoFilter filter = sheet.getInternalSheet().getAutoFilter();
		final int index = (Integer) ctx.getData("field") - 1;
		final NFilterColumn fc = filter.getFilterColumn(index, false);		
		
		Top10FilterCtrl.show(new SerializableEventListener<DialogCallbackEvent>() {
			private static final long serialVersionUID = 1L;

			// When press the OK button
			@Override
			public void onEvent(DialogCallbackEvent event) throws Exception {
				Map<String, Object> data = event.getData();
				if(data != null) {	
					final boolean isTop = (Boolean) data.get(Top10FilterCtrl.ARG_TOPBOTTOM);
					final boolean isPercent = (Boolean) data.get(Top10FilterCtrl.ARG_ITEMSPERCENT);
					final AutoFilterOperation opx =
							isTop ? 
							(isPercent ? 
								AutoFilterOperation.TOP10PERCENT :
								AutoFilterOperation.TOP10) :
							(isPercent ?
								AutoFilterOperation.BOTTOM10PERCENT :
								AutoFilterOperation.BOTTOM10);
					final double value = (Double) data.get(Top10FilterCtrl.ARG_VALUE);
					final Object [] criteria1 = new Object[] {Integer.valueOf((int)value)}; //ZSS-1234
					final Integer[] criteria2 = null;
					Ranges.range(sheet).enableAutoFilter(index+1, 
							opx, criteria1, criteria2, true);
				}
			}
		}, fc);
		
		return true;
	}

}