/* CustomSortHandler.java

{{IS_NOTE
	Purpose:
		
	Description:
		
	History:
		2013/8/5 , Created by dennis
}}IS_NOTE

Copyright (C) 2013 Potix Corporation. All Rights Reserved.

{{IS_RIGHT
}}IS_RIGHT
*/
package org.zkoss.zssex.ui.impl.ua;

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.Hyperlink;
import org.zkoss.zss.api.model.Sheet;
import org.zkoss.zss.api.model.Hyperlink.HyperlinkType;
import org.zkoss.zss.ui.UserActionContext;
import org.zkoss.zss.ui.impl.ua.AbstractHandler;
import org.zkoss.zssex.ui.dialog.InsertHyperlinkCtrl;
import org.zkoss.zssex.ui.dialog.impl.DialogCallbackEvent;

/**
 * @author dennis
 *
 */
public class HyperlinkHandler extends AbstractHandler {
	private static final long serialVersionUID = -1852968828824632170L;

	/* (non-Javadoc)
	 * @see org.zkoss.zss.ui.sys.ua.impl.AbstractHandler#processAction(org.zkoss.zss.ui.UserActionContext)
	 */
	@Override
	protected boolean processAction(UserActionContext ctx) {
		final Sheet sheet = ctx.getSheet();
		final AreaRef selection = ctx.getSelection();
		Range range = Ranges.range(sheet, selection.getRow(), selection.getColumn());
		if (range.isProtected()) {
			showProtectMessage();
			return true;
		}
		Hyperlink link = range.getCellHyperlink();
		String display = link==null?range.getCellFormatText():link.getLabel();
		String address = link==null?null:link.getAddress();
		HyperlinkType type = link==null?null:link.getType();
		
		InsertHyperlinkCtrl.show(new SerializableEventListener<DialogCallbackEvent>(){
			private static final long serialVersionUID = -3649564402999485961L;

			@Override
			public void onEvent(DialogCallbackEvent event) throws Exception {
				if(InsertHyperlinkCtrl.ON_OK.equals(event.getName())){
					String label = (String)event.getData(InsertHyperlinkCtrl.ARG_DISPLAY);
					String address = (String)event.getData(InsertHyperlinkCtrl.ARG_ADDRESS);
					HyperlinkType type = (HyperlinkType)event.getData(InsertHyperlinkCtrl.ARG_LINKTYPE);
					
					CellOperationUtil.applyHyperlink(Ranges.range(sheet,selection), type, address, label);
				}
			}}, type, address, display, ctx.getSpreadsheet());
		return true;
	}

	@Override
	public boolean isEnabled(Book book, Sheet sheet) {
		// TODO enable only when the range is unlocked
		return book != null && sheet != null && ( !sheet.isProtected() ||
				Ranges.range(sheet).getSheetProtection().isInsertHyperlinksAllowed());
	}

}
