/*
 * Copyright 2006 Maskat Project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.maskat.ide.action;

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;

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("Cut");
		setToolTipText("Cut");
		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();
		if (cmd == null)
			return false;
		return 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());
	}
}
