/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.ui.editors.layout.tools;

import org.eclipse.draw2d.Cursors;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.tools.TargetingTool;
import org.eclipse.gef.ui.parts.TreeViewer;
import org.eclipse.swt.graphics.Cursor;

import org.maskat.ui.editors.layout.requests.DataBindingRequest;
import org.maskat.ui.views.properties.tabbed.masterdetails.ISimpleCallbackInterface;

public class DataBindingTool extends TargetingTool {
	
	ISimpleCallbackInterface callbackReference;
	
	protected Object bean;
	
	protected String propertyName;
	
	private Cursor defaultCursor;
	
	public DataBindingTool(Object bean, String propertyName) {
		super();
		this.bean = bean;
		this.propertyName = propertyName;

		this.defaultCursor = getDefaultCursor();
		setDefaultCursor(Cursors.HAND);
		setDisabledCursor(Cursors.NO);
	}
	
	public void registerCallback(ISimpleCallbackInterface callbackRefrence)
	{
		this.callbackReference = callbackRefrence;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.tools.TargetingTool#createTargetRequest()
	 */
	protected Request createTargetRequest() {
		return new DataBindingRequest(bean, propertyName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.tools.AbstractTool#getCommandName()
	 */
	protected String getCommandName() {
		return DataBindingRequest.REQ_DATA_BINDING;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.tools.AbstractTool#calculateCursor()
	 */
	protected Cursor calculateCursor() {
		if (isInState(STATE_INITIAL) && getTargetEditPart() != null) {
			return getDefaultCursor();
		}
		if (getCurrentViewer() instanceof TreeViewer) {
			return Cursors.ARROW;
		}
		return getDisabledCursor();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.tools.AbstractTool#handleMove()
	 */
	protected boolean handleMove() {
		if (isInState(STATE_INITIAL)) {
			updateTargetUnderMouse();
			setCurrentCommand(getCommand());
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.tools.AbstractTool#handleButtonDown(int)
	 */
	protected boolean handleButtonDown(int button) {
		if (stateTransition(STATE_INITIAL, STATE_TERMINAL)) {
			Command command = getCommand();
			if (command != null && command.canExecute()) {
				setCurrentCommand(command);
				executeCurrentCommand();
			}
			releaseToolCapture();
			setDefaultCursor(defaultCursor);
			
			callbackReference.callback(true);
			
			return true;
		}
		
		callbackReference.callback(false);
		
		return false;
	}

}
