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

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

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;
import org.maskat.core.layout.Component;
import org.maskat.core.layout.Container;

public class OrphanChildrenCommand extends Command {

	private List components;
	
	private List oriParents;
	
	private List oriConstraints;
	
	private List 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++) {
			Component comp = (Component) components.get(i);
			oriParents.add(comp.getContainer());
			Rectangle constraint = new Rectangle(comp.getLeft(), comp.getTop(), comp
					.getWidth(), comp.getHeight());
			
			// 現親部品との位置関係constraintが残される、undoの時、元の位置に戻るため
			oriConstraints.add(constraint);
			oriIndices.add(new Integer(comp.getContainer().getChildIdx(comp)));
			
			// 現親部品から離れる
			comp.getContainer().removeChild(comp);
		}
	}

	public boolean canExecute() {
		return true;
	}

	public boolean canUndo() {
		return true;
	}

	public void undo() {
		for (int i = 0; i < components.size(); i++) {
			Component comp = (Component) components.get(i);
			Container oriParent = (Container) 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);
		}
	}
}
