/*
 * 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.event.EventDef;
import org.maskat.core.layout.Component;
import org.maskat.core.layout.TabFolder;
import org.maskat.core.layout.TabItem;
import org.maskat.ui.editors.layout.models.TabDef;

public class DelBasicDefCommand extends Command {
	
	private MaskatElement parent;

	private MaskatElement child;

	private int index;

	private EventDef eventDef;

	private org.maskat.core.event.Component eventComponent;

	private boolean noAction = false;

	public DelBasicDefCommand(MaskatElement parent, MaskatElement child) {
		this.parent = parent;
		this.child = child;
	}

	public void execute() {
		index = parent.getChildIdx(child);
		if (index == -1) {
			if ((child instanceof TabItem || child instanceof TabDef)
					&& parent instanceof TabFolder) {
				noAction = true;
				// TabとTabItemとも選択し、削除する場合対応
				return; 
			}
			throw new IllegalStateException(
					"Cannot delete without child-parent relationship.");
		}
		parent.removeChild(child);

		if (child instanceof Component) {
			Component component = (Component) child;
			eventDef = component.getLayout().getLayoutDef().getEventDef();
			eventComponent = eventDef.findComponent(component.getName());
			if (eventComponent != null) {
				eventDef.removeChild(eventComponent);
			}
		}
	}

	public void undo() {
		if (noAction) {
			return;
		}

		parent.addChildToIdx(child, index);
		if (eventDef != null && eventComponent != null) {
			eventDef.addChild(eventComponent);
		}
	}

	public boolean canUndo() {
		return true;
	}
}
