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

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.XYLayoutEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.maskat.framework.IBasicDef;
import org.maskat.framework.screendef.LayoutDef;
import org.maskat.framework.screendef.TreeNodeDef;
import org.maskat.ide.gef.commands.AddBasicDefCommand;

public class TreeNodeXYLayoutEditPolicy extends XYLayoutEditPolicy {

	protected Command createAddCommand(EditPart child, Object constraint) {
		IBasicDef host = (IBasicDef) getHost().getModel();
		Object childModel = child.getModel();

		if (!(childModel instanceof TreeNodeDef)) {
			return null;
		}
		if (host.getChildIdx(childModel) != -1)
			return null;// 本来の親子だったら、コマンドを発行する必要ない
		IBasicDef childDef = (IBasicDef) childModel;
		IBasicDef parent = host.getParentDef(); // childDefはhostの親ノードの場合、逆に指定することはできない
		while (parent != null) {
			if (parent == childDef) {
				return null;
			}
			parent = parent.getParentDef();
		}

		return new AddBasicDefCommand(host, (TreeNodeDef) childModel);
	}

	protected Command createChangeConstraintCommand(EditPart child, Object constraint) {
		return null;
	}

	protected Command getCreateCommand(CreateRequest request) {
		TreeNodeDef host = (TreeNodeDef) getHost().getModel();
		Object newObj = request.getNewObject();

		if (!(newObj instanceof TreeNodeDef)) {
			return null;
		}

		TreeNodeDef treeNode = (TreeNodeDef) newObj;
		LayoutDef layoutDef = host.getLayoutDef();
		layoutDef.setAppropriateNameForComponent(treeNode);

		return new AddBasicDefCommand(host, treeNode);
	}

	protected Command getDeleteDependantCommand(Request request) {
		return null;
	}

}
