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.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.AbstractCellHandler;
import org.zkoss.zss.ui.sys.UndoableActionManager;
import org.zkoss.zssex.ui.dialog.RichTextEditCtrl;
import org.zkoss.zssex.ui.dialog.impl.DialogCallbackEvent;
import org.zkoss.zssex.ui.impl.undo.CellCommentAction;

public abstract class AbstractCommentHandler extends AbstractCellHandler {
	private static final long serialVersionUID = 4307892026544541736L;

	public AbstractCommentHandler() {
		super();
	}

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

			@Override
			public void onEvent(DialogCallbackEvent event) throws Exception {
				if (RichTextEditCtrl.ON_OK.equals(event.getName())) {
					final String content = (String) event.getData(RichTextEditCtrl.ARG_CONTENT);
					
					UndoableActionManager uam = ctx.getSpreadsheet().getUndoableActionManager();
					uam.doAction(new CellCommentAction(Labels.getLabel("zss.undo.insertComment"),sheet,row,column,row,column,content));
				}
			}}, getTitle(), range.getCommentRichText(), ctx.getSpreadsheet());
		return true;
	}

	protected abstract String getTitle();
}