package org.zkoss.zssex.ui.impl.ua;

import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.SerializableEventListener;
import org.zkoss.zss.api.CellOperationUtil;
import org.zkoss.zss.api.Range;
import org.zkoss.zss.api.Ranges;
import org.zkoss.zss.api.AreaRef;
import org.zkoss.zss.api.model.Book;
import org.zkoss.zss.api.model.Sheet;
import org.zkoss.zss.api.model.SheetProtection;
import org.zkoss.zss.ui.UserActionContext;
import org.zkoss.zss.ui.impl.ua.AbstractHandler;
import org.zkoss.zss.ui.impl.ua.AbstractSheetHandler;
import org.zkoss.zss.ui.impl.undo.ResizeHeaderAction;
import org.zkoss.zss.ui.sys.UndoableActionManager;
import org.zkoss.zssex.ui.dialog.HeaderSizeCtrl;
import org.zkoss.zssex.ui.dialog.HeaderSizeCtrl.HeaderType;
import org.zkoss.zssex.ui.dialog.impl.DialogCallbackEvent;

public class HeaderSizeHandler extends AbstractHandler {
	private static final long serialVersionUID = -4438278621658453175L;
	private final HeaderSizeCtrl.HeaderType _headerType;
	
	public HeaderSizeHandler(HeaderSizeCtrl.HeaderType headerType){
		this._headerType = headerType;
	}
	
	@Override
	protected boolean processAction(final UserActionContext ctx) {
		final Sheet sheet = ctx.getSheet();
		final AreaRef selection = ctx.getSelection();
		int size = _headerType==HeaderType.COLUMN?
				sheet.getColumnWidth(selection.getColumn()):sheet.getRowHeight(selection.getRow());

		HeaderSizeCtrl.show(new SerializableEventListener<DialogCallbackEvent>(){
			private static final long serialVersionUID = -8392523484662788558L;

			@Override
			public void onEvent(DialogCallbackEvent event) throws Exception {
				if(HeaderSizeCtrl.ON_OK.equals(event.getName())){
					int size = (Integer)event.getData(HeaderSizeCtrl.ARG_HEADER_SIZE);
					String label = _headerType==HeaderType.COLUMN?
							Labels.getLabel("zss.undo.columnSize"):Labels.getLabel("zss.undo.rowSize");
					ResizeHeaderAction.Type action = _headerType==HeaderType.COLUMN?
							ResizeHeaderAction.Type.COLUMN:ResizeHeaderAction.Type.ROW;
					
					UndoableActionManager uam = ctx.getSpreadsheet().getUndoableActionManager();
					uam.doAction(new ResizeHeaderAction(label,sheet, selection.getRow(), selection.getColumn(), 
						selection.getLastRow(), selection.getLastColumn(), 
						action,size, true));
				}
			}}, _headerType, size, ctx.getSpreadsheet());
		return true;
	}

	@Override
	public boolean isEnabled(Book book, Sheet sheet) {
		if (book == null || sheet == null) {
			return false;
		}
		if (!sheet.isProtected()) {
			return true;
		}
		final SheetProtection sheetProtection = Ranges.range(sheet).getSheetProtection();
		boolean allowed = false;
		switch(_headerType){
		case COLUMN:
			allowed = sheetProtection.isFormatColumnsAllowed();
			break;
		case ROW:
			allowed = sheetProtection.isFormatRowsAllowed();
			break;
		}
		return allowed;
	}

}
