/**
 * File:    CustomMethodPropertyDescriptorFactory.java
 * Created: 22.09.2008
 *
 *
/*******************************************************************************
 * Copyright (c) 2008   Open Wide SA
 *
 * 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
 *
 *    Mickael Istria, Open Wide, France
 *      - Creation and Implementation
 *******************************************************************************/


package org.eclipse.jwt.we.helpers.app.editors.properties.method;


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

import org.eclipse.emf.common.ui.celleditor.ExtendedComboBoxCellEditor;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.ui.provider.PropertyDescriptor;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jwt.meta.model.application.Application;
import org.eclipse.jwt.meta.model.application.ApplicationPackage;
import org.eclipse.jwt.we.helpers.app.jdt.JDTTools;
import org.eclipse.swt.widgets.Composite;


public class CustomMethodPropertyDescriptor extends PropertyDescriptor {

	private Application application;

	/**
	 * The constructor.
	 * 
	 * @param object
	 *            The object.
	 * @param itemPropertyDescriptor
	 *            The itemPropertyDescriptor.
	 */
	public CustomMethodPropertyDescriptor(Object application,
			IItemPropertyDescriptor itemPropertyDescriptor) {
		super(application, itemPropertyDescriptor);
		this.application = (Application)application;
	}

	public CellEditor createPropertyEditor(Composite parent) {
		CellEditor methodEditor = null;
		try {
			List<IMethod> methods =JDTTools.getMethodList(application.getJavaClass(), JDTTools.getJavaProject(application));
			if (methods.size() > 0) {
				methodEditor = new ExtendedComboBoxCellEditor(parent, getComboEntriesFromMethods(methods), new MethodNameLabelProvider(methods));
			} else {
				methodEditor = new EDataTypeCellEditor((EDataType)(ApplicationPackage.Literals.APPLICATION__METHOD.getEType()), parent);
			}
		} catch (JavaModelException ex) {
			System.err.println("Class [" + ((Application)application).getJavaClass() + "] could not be found in specified runtime class path"); //$NON-NLS-1$ //$NON-NLS-2$
		}
		if (methodEditor == null)
			methodEditor = new EDataTypeCellEditor((EDataType)(ApplicationPackage.Literals.APPLICATION__METHOD.getEType()), parent);
		return methodEditor;
	}
	
	public static List<String> getComboEntriesFromMethods(List<IMethod> methods) {
		List<String> res = new ArrayList<String>();
		for (IMethod method : methods)
			res.add(method.getElementName());
		return res;
	}

}