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

import org.maskat.core.MaskatElement;
import org.maskat.core.layout.Component;
import org.maskat.core.layout.Layout;
import org.maskat.ui.Messages;
import org.maskat.ui.editors.layout.tools.ComponentUtils;

public class AddBasicDefCommand extends Command {

	private MaskatElement parent;

	private MaskatElement child;

	private MaskatElement originalParent;

	private int originalIdx;

	public AddBasicDefCommand(MaskatElement parent, MaskatElement child) {
		super(Messages.getString("layout.cmd.add.msg.title")); //$NON-NLS-1$
		this.parent = parent;
		this.child = child;
	}

	public void execute() {
		originalParent = child.getParent();
		if (originalParent != null) {
			originalIdx = originalParent.getChildIdx(child);
	
			if (originalIdx == -1) {
				// childはoriginalParentの子ノードではない
				originalParent = null;
			} else {
				// childはoriginalParentの子ノードだ
				originalParent.removeChild(child);
			}
		} else {
			Layout layout = ((Component) parent).getLayout();
			ComponentUtils.setUniqueName(layout, (Component) child);
		}
		parent.addChild(child);
	}

	public void undo() {
		parent.removeChild(child);
		if (originalParent != null) {
			originalParent.addChildToIdx(child, originalIdx);
		}
	}

	public boolean canUndo() {
		return true;
	}
}
