/*
 * 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 org.eclipse.gef.commands.Command;
import org.maskat.framework.IBasicDef;
import org.maskat.framework.eventdef.Component;
import org.maskat.framework.eventdef.Layout;
import org.maskat.framework.screendef.IComponentDef;
import org.maskat.framework.screendef.TabFolderDef;
import org.maskat.framework.screendef.TabItemDef;
import org.maskat.ide.gef.models.TabDef;

public class DelBasicDefCommand extends Command {
	private IBasicDef parent;

	private IBasicDef child;

	private int idx;

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

	private Layout layout;

	private Component comp;

	private boolean noAction = false;

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

		if (child instanceof IComponentDef) {
			IComponentDef comDef = (IComponentDef) child;
			Layout[] layouts = comDef.getLayoutDef().getLayoutEvtDefSrc().getDefs();
			for (int i = 0; i < layouts.length; i++) {
				Component comp = layouts[i].findComponent(comDef.getName());
				if (layouts[i].findComponent(comDef.getName()) != null) {
					layout = layouts[i];
					this.comp = comp;
					layouts[i].removeChild(comp);
					return;
				}
			}
		}
	}

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

		parent.addChildToIdx(child, idx);
		if (layout != null) {
			layout.addChild(comp);
		}
	}

	public boolean canUndo() {
		return true;
	}
}
