/*
 * 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.editpolicies;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.AbstractEditPolicy;

import org.maskat.core.layout.Component;
import org.maskat.ui.editors.layout.commands.SetPropertyCommand;
import org.maskat.ui.editors.layout.requests.DataBindingRequest;

public class DataBindingEditPolicy extends AbstractEditPolicy {
	
	public static final String ROLE = "data binding";

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.editpolicies.AbstractEditPolicy#getTargetEditPart(org.eclipse.gef.Request)
	 */
	public EditPart getTargetEditPart(Request request) {
		if (request instanceof DataBindingRequest) {
			return getHost();
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.editpolicies.AbstractEditPolicy#getCommand(org.eclipse.gef.Request)
	 */
	public Command getCommand(Request request) {
		if (DataBindingRequest.REQ_DATA_BINDING.equals(request.getType())) {
			return createDataBindingCommand((DataBindingRequest) request);
		}
		return null;
	}

	protected Command createDataBindingCommand(DataBindingRequest request) {
		EditPart editPart = getTargetEditPart(request);
		if (editPart != null) {
			String value = ((Component) editPart.getModel()).getName();
			return new SetPropertyCommand(request.getBean(), request.getPropertyName(),
					value);
		}
		return null;
	}

}
