/* HideSheetHandler.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 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;

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

	@Override
	public boolean isEnabled(Book book, Sheet sheet) {
		if(book == null)
			return false;
		
		int count = 0;
		for(int i = 0, length = book.getNumberOfSheets(); i < length; i++) {
			Sheet s = book.getSheetAt(i);
			if(!(s.isHidden() || s.isVeryHidden()))
				count++;
		}
		return count > 1;
	}

	@Override
	protected boolean processAction(final UserActionContext ctx) {
		Book book = ctx.getBook();
		int len = book.getNumberOfSheets();
		int index = book.getSheetIndex(ctx.getSheet());
		index = findAvailableCandidate(book, index, len);
		
		Ranges.range(ctx.getSheet()).setSheetVisible(SheetVisible.HIDDEN);
		ctx.getSpreadsheet().setSelectedSheet(book.getSheetAt(index).getSheetName());
		
		return true;
	}
	
	private int findAvailableCandidate(Book book, int index, int length) {
		// from index to tail
		for(int i = index + 1; i < length; i++) {
			if(!isHidden(book.getSheetAt(i)))
				return i;
		}
		
		// from index to 0
		for(int i = index - 1; i >= 0; i--) {
			if(!isHidden(book.getSheetAt(i)))
				return i;
		}
		
		return -1;
	}
	
	private boolean isHidden(Sheet sheet) {
		return sheet.isHidden() || sheet.isVeryHidden();
	}

}