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

import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.event.SerializableEventListener;
import org.zkoss.zss.api.AreaRef;
import org.zkoss.zss.api.IllegalFormulaException;
import org.zkoss.zss.api.Range;
import org.zkoss.zss.api.Ranges;
import org.zkoss.zss.api.model.Sheet;
import org.zkoss.zss.ui.UserActionContext;
import org.zkoss.zss.ui.impl.ua.AbstractProtectedHandler;
import org.zkoss.zssex.ui.dialog.InsertFormulaCtrl;
import org.zkoss.zssex.ui.dialog.impl.DialogCallbackEvent;
import org.zkoss.zul.Messagebox;

public class InsertFunctionHandler extends AbstractProtectedHandler {
	private static final long serialVersionUID = 555113506918283081L;

	@Override
	protected boolean processAction(UserActionContext ctx) {
		final Sheet sheet = ctx.getSheet();
		final AreaRef selection = ctx.getSelection();
		final Range selectedCell = Ranges.range(sheet, selection.getRow(), selection.getColumn());
		
		InsertFormulaCtrl.show(new SerializableEventListener<DialogCallbackEvent>(){
			private static final long serialVersionUID = -6203591694383610317L;

			@Override
			public void onEvent(DialogCallbackEvent event) throws Exception {
				if(InsertFormulaCtrl.ON_OK.equals(event.getName())){
					String formula = (String)event.getData(InsertFormulaCtrl.FORMULA);
					try{
						selectedCell.setCellEditText(formula);
					}catch (IllegalFormulaException x) {
						showFormulaError((IllegalFormulaException)x);
					}
				}
			}});
		return true;
	}
	
	private void showFormulaError(IllegalFormulaException ex) {
		String title = Labels.getLabel("zss.msg.warn_title");
		String msg = Labels.getLabel("zss.msg.formula_error",new Object[]{ex.getMessage()});
		Messagebox.show(msg, title, Messagebox.OK, Messagebox.EXCLAMATION,null);
	}
}
