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

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.requests.GroupRequest;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.maskat.ui.Messages;

public class CutComponentAction extends CopyComponentAction {

	private static Request request = new GroupRequest(RequestConstants.REQ_DELETE);

	public CutComponentAction(IWorkbenchPart part) {
		super(part);
		setId(ActionFactory.CUT.getId());
		setText(Messages.getString("layout.cmd.cut.msg.title")); //$NON-NLS-1$
		setToolTipText(Messages.getString("layout.cmd.cut.msg.title")); //$NON-NLS-1$
		ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
		setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
		setDisabledImageDescriptor(
				sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_DISABLED));
	}

	protected boolean calculateEnabled() {
		if (!super.calculateEnabled()) {
			return false;
		}

		Command cmd = createDeleteCommand();
		return (cmd != null) && cmd.canExecute();
	}

	protected List getOperationSet() {
		List editparts = new ArrayList(getSelectedObjects());
		if (editparts.isEmpty() || !(editparts.get(0) instanceof GraphicalEditPart)) {
			return Collections.EMPTY_LIST;
		}
		// editparts = ToolUtilities.getSelectionWithoutDependants(editparts);

		// ToolUtilities.filterEditPartsUnderstanding(editparts, request);
		return editparts;
	}

	private Command createDeleteCommand() {
		List operationSet = getOperationSet();

		CompoundCommand command = new CompoundCommand();
		command.setDebugLabel(getText());
		for (int i = 0; i < operationSet.size(); i++) {
			EditPart editpart = (EditPart) operationSet.get(i);
			command.add(editpart.getCommand(request));
		}
		return command;
	}

	public void run() {
		super.run();
		execute(createDeleteCommand());
	}
}
