/*******************************************************************************
 * Copyright (c) 2000, 2003 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package APStudio.models.commands;

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

import org.eclipse.gef.commands.Command;
import APStudio.models.BasicSubpart;
import APStudio.models.ClassGraphModel;
import APStudio.models.Connector;
import APStudio.ResourceMgtUtils;
public class DeleteCommand
	extends Command
{

private BasicSubpart child;
private ClassGraphModel parent;
private int index = -1;
private List sourceConnections = new ArrayList();
private List targetConnections = new ArrayList();

public DeleteCommand() {
	super("DeleteCommand");
}

private void deleteConnections(BasicSubpart part) {
	if (part instanceof ClassGraphModel) {
		List children = ((ClassGraphModel)part).getChildren();
		for (int i = 0; i < children.size(); i++)
			deleteConnections((BasicSubpart)children.get(i));
	}
	sourceConnections.addAll(part.getSourceConnections());
	for (int i = 0; i < sourceConnections.size(); i++) {
		Connector wire = (Connector)sourceConnections.get(i);
		wire.detachSource();
		wire.detachTarget();
	}
	targetConnections.addAll(part.getTargetConnections());
	for (int i = 0; i < targetConnections.size(); i++) {
		Connector wire = (Connector)targetConnections.get(i);
		wire.detachSource();
		wire.detachTarget();
	}
}

public void execute() {
	primExecute();
}

/**
 * When a node is deleted delete the corresponding 
 * connections and remove the respective java file
 *
 */
protected void primExecute() {
	deleteConnections(child);
	index = parent.getChildren().indexOf(child);
	parent.removeChild(child);
	//remove the java file from the file system.
	String name = child.getName();
	//Add the extension
	name = name + ".java";
	ResourceMgtUtils.removeFile(name);
}


public void redo() {
	primExecute();
}

private void restoreConnections() {
	for (int i = 0; i < sourceConnections.size(); i++) {
		Connector wire = (Connector)sourceConnections.get(i);
		wire.attachSource();
		wire.attachTarget();
	}
	sourceConnections.clear();
	for (int i = 0; i < targetConnections.size(); i++) {
		Connector wire = (Connector)targetConnections.get(i);
		wire.attachSource();
		wire.attachTarget();
	}
	targetConnections.clear();
}

public void setChild (BasicSubpart c) {
	child = c;
}

public void setParent(ClassGraphModel p) {
	parent = p;
}

public void undo() {
	parent.addChild(child, index);
	restoreConnections();
}

}
