/* UnhideSheetHandler.java

{{IS_NOTE
	Purpose:
		
	Description:
		
	History:
		2014/11/14 , Created by jerrychen
}}IS_NOTE

Copyright (C) 2014 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.Ranges;
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.ui.UserActionContext;
import org.zkoss.zss.ui.impl.ua.AbstractBookHandler;
import org.zkoss.zssex.ui.dialog.UnhideSheetCtrl;
import org.zkoss.zssex.ui.dialog.impl.DialogCallbackEvent;

/**
 * @author jerrychen
 * @since 3.7.0
 */
public class UnhideSheetHandler extends AbstractBookHandler{
	private static final long serialVersionUID = 4133139451894267942L;

	@Override
	public boolean isEnabled(Book book, Sheet sheet) {
		if(book == null)
			return false;
		
		for(int i = 0, length = book.getNumberOfSheets(); i < length; i++) {
			if(book.getSheetAt(i).isHidden())
				return true;
		}
		return false;
	}

	@Override
	protected boolean processAction(final UserActionContext ctx) {
		Book book = ctx.getBook();
		int len = book.getNumberOfSheets();
			
		List<String> names = new ArrayList<String>(len);

		for (int i = 0; i < len; i++) {
			Sheet sheet = book.getSheetAt(i);
			if(sheet.isHidden())				
				names.add(sheet.getSheetName());
		}

		UnhideSheetCtrl.show(new SerializableEventListener<DialogCallbackEvent>() {
			private static final long serialVersionUID = 8416857558958915359L;

			@Override
			public void onEvent(DialogCallbackEvent event) throws Exception {
				Map<String, Object> data = event.getData();
				if(data != null) {		
					List<String> nameList = (List<String>) data.get(UnhideSheetCtrl.ARG_SHEET_NAMES);
					int size = nameList.size();
					
					if(size > 0) {
						for(String name: nameList)
							Ranges.range(ctx.getBook().getSheet(name)).setSheetVisible(SheetVisible.VISIBLE); 

						ctx.getSpreadsheet().setSelectedSheet(nameList.get(size - 1));
					}
				}
			}
		}, names);
		
		return true;
	}

}