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

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartFactory;

import org.maskat.ui.MaskatUIPlugin;

public class ChainedEditPartFactory implements EditPartFactory {

	private EditPartFactory[] factories;

	public ChainedEditPartFactory() {
		super();
		init();
	}

	private void init() {
		IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(
				MaskatUIPlugin.PLUGIN_ID, "editPartFactories"); //$NON-NLS-1$
		IExtension[] extensions = point.getExtensions();
		List result = new ArrayList();
		for (int i = 0; i < extensions.length; i++) {
			IConfigurationElement[] elements = extensions[i].getConfigurationElements();
			for (int j = 0; j < elements.length; j++) {
				try {
					IConfigurationElement element = elements[j];
					if ("factory".equals(element.getName())) { //$NON-NLS-1$
						result.add(element.createExecutableExtension("class")); //$NON-NLS-1$
					}
				} catch (CoreException e) {
					MaskatUIPlugin.log(e.getStatus());
				}
			}
		}
		result.add(new DynaComponentEditPartFactory());
		
		factories = (EditPartFactory[]) result
				.toArray(new EditPartFactory[result.size()]);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.EditPartFactory#createEditPart(org.eclipse.gef.EditPart,
	 *      java.lang.Object)
	 */
	public EditPart createEditPart(EditPart context, Object model) {
		if (factories == null) {
			return null;
		}

		EditPart editPart = null;
		for (int i = 0; i < factories.length; i++) {
			editPart = factories[i].createEditPart(context, model);
			if (editPart != null) {
				return editPart;
			}
		}
		return null;
	}

}
