//------------------------------------------------------------------------------
// Copyright (c) 2005, 2006 IBM Corporation and others.
// 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:
// IBM Corporation - initial implementation
//------------------------------------------------------------------------------
package org.eclipse.epf.library.edit.itemsfilter;

import java.util.Collection;
import java.util.Iterator;

import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.epf.library.edit.IConfigurable;
import org.eclipse.epf.library.edit.IFilter;
import org.eclipse.epf.uma.ContentPackage;

/**
 * The item provider adapter for a content package in the method element
 * selection dialogs.
 * 
 * @author Phong Nguyen Le
 * @author Shashidhar Kannoori
 * @since 1.0
 */
public class ContentPackageItemProvider extends
		org.eclipse.epf.uma.provider.ContentPackageItemProvider implements
		IConfigurable {

	private IFilter filter;

	/**
	 * Creates a new instance.
	 */
	public ContentPackageItemProvider(AdapterFactory adapterFactory) {
		super(adapterFactory);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.emf.edit.provider.ItemProviderAdapter#getChildren(java.lang.Object)
	 */
	public Collection getChildren(Object object) {
		Collection children = getChildrenIncludingEmptyOnes(object);

		// remove the empty packages from the children list
		//
		for (Iterator iter = children.iterator(); iter.hasNext();) {
			if (isEmptyPackage(iter.next())) {
				iter.remove();
			}
		}

		return children;
	}

	private Collection getChildrenIncludingEmptyOnes(Object object) {
		Collection children = super.getChildren(object);
		if (filter != null) {
			for (Iterator iter = children.iterator(); iter.hasNext();) {
				if (!filter.accept(iter.next())) {
					iter.remove();
				}

			}
		}
		return children;
	}

	/**
	 * @param object
	 * @return
	 */
	private boolean isEmptyPackage(Object object) {
		if (!(object instanceof ContentPackage))
			return false;
		Collection children = this.getChildrenIncludingEmptyOnes(object);
		for (Iterator iter = children.iterator(); iter.hasNext();) {
			if (!isEmptyPackage(iter.next())) {
				return false;
			}
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.epf.library.edit.IConfigurable#setFilter(com.ibm.library.edit.IFilter)
	 */
	public void setFilter(IFilter filter) {
		this.filter = filter;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.epf.library.edit.IConfigurable#setLabel(java.lang.String)
	 */
	public void setLabel(String label) {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.epf.library.edit.IConfigurable#setParent(java.lang.Object)
	 */
	public void setParent(Object parent) {
	}

}
