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

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

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;
import org.maskat.framework.screendef.IComponentDef;
import org.maskat.framework.screendef.IContainerDef;

public class OrphanChildrenCommand extends Command {

	private List components, oriParents, oriConstraints, oriIndices;

	public OrphanChildrenCommand(List components) {
		this.components = components;
	}

	public void execute() {
		oriParents = new ArrayList();
		oriConstraints = new ArrayList();
		oriIndices = new ArrayList();
		for (int i = 0; i < components.size(); i++) {
			IComponentDef comp = (IComponentDef) components.get(i);
			oriParents.add(comp.getParent());
			Rectangle constraint = new Rectangle(comp.getLeft(), comp.getTop(), comp
					.getWidth(), comp.getHeight());
			// 現親部品との位置関係constraintが残される、undoの時、元の位置に戻るため
			oriConstraints.add(constraint);
			oriIndices.add(new Integer(comp.getParent().getChildIdx(comp)));
			// 現親部品から離れる
			comp.getParent().removeChild(comp);
		}
	}

	public boolean canExecute() {
		return true;
	}

	public boolean canUndo() {
		return true;
	}

	public void undo() {
		for (int i = 0; i < components.size(); i++) {
			IComponentDef comp = (IComponentDef) components.get(i);
			IContainerDef oriParent = (IContainerDef) oriParents.get(i);
			Rectangle cons = (Rectangle) oriConstraints.get(i);
			comp.setConstraint(cons.x, cons.y, cons.width, cons.height);
			// 元親部品に
			int oriIndex = ((Integer) oriIndices.get(i)).intValue();
			oriParent.addChildToIdx(comp, oriIndex);
		}
	}
}
