/*
 * 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.views.properties.tabbed.treenodewrapper;

import java.util.ArrayList;

import org.maskat.core.MaskatElement;
import org.maskat.ui.Messages;
import org.maskat.ui.views.properties.tabbed.action.DeleteOneNodeAction;

import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.TreeViewer;

public class AbstractTreeNode implements ITreeNode {
	private static final String DISPLAY_TEXT =
		Messages.getString("abstractTreeNode.displayText"); //$NON-NLS-1$	
	
	protected MaskatElement maskatElement;
	
	private ITreeNode parent;
	
	private ArrayList children = new ArrayList();
	
	public AbstractTreeNode(MaskatElement maskatElement) {
		this.maskatElement = maskatElement;
		if (maskatElement != null) {
			loadChildren();
		}
	}
	
	public void setModel(MaskatElement model) {
		this.maskatElement = model;
	}
	
	public MaskatElement getModel() {
		return maskatElement;
	}
	
	public String getImage() {
		return null;
	}
	
	public String getDisplayText() {
		return DISPLAY_TEXT;
	}

	public IMenuManager fillContextMenu(final TreeViewer treeViewer, IMenuManager manager) {
		if(isDeletable()) {
			if(manager.getItems().length > 0) {
				manager.add(new Separator());
			}
			manager.add(new DeleteOneNodeAction(treeViewer,this));
		}
		return manager;
	}
	
	public void addChild(ITreeNode child) {
		if(children.contains(child)) {
			return;
		}
		children.add(child);
		child.setParent(this);
	}

	public ITreeNode getParent() {
		return parent;
	}
	
	public void setParent(ITreeNode parent) {
		this.parent = parent;
	}
	
	public Object[] getChildren() {
		return children.toArray();
	}

	public boolean hasChildren() {
		return children.size() > 0;
	}
	
	public void clearChildren() {
		children.clear();
	}
	
	public void removeChild(ITreeNode child) {
		children.remove(child);
		child.setParent(null);
	}
	
	public boolean containsChild(Class childClass) {
		for(int i=0; i<children.size(); i++) {
			if(childClass.equals(children.get(i).getClass())) {
				return true;
			}
		}
		return false;
	}
	
	public boolean isDeletable() {
		return true;
	}
	
	public boolean isCopiable() {
		return false;
	}
	
	public boolean canPasteTo(ITreeNode parent) {
		return false;
	}
	
	protected void loadChildren() {
		//default to do nothing
	}

}
