/**
 * File:    MethodNameLabelProvider.java
 * Created: 26.03.2009
 *
 *
/*******************************************************************************
 * Copyright (c) 2008-2009   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
 *      - Use of JDT to introspect classes
 *******************************************************************************/

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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.swt.graphics.Image;

/**
 * Class in charge of associating labels to methods to display
 * method signatures in choose list
 * @author mistria
 *
 */
public class MethodNameLabelProvider implements ILabelProvider {
	
	private List<IMethod> methods;
	
	public MethodNameLabelProvider(List<IMethod> methods) {
		this.methods = methods;
	}

	public Image getImage(Object element) {
		return null;
	}

	public String getText(Object element) {
		int index = getMethodId(element);
		IMethod method = methods.get(index);
		try {
			return Signature.toString(method.getSignature(), method.getElementName(), method.getParameterNames(), false, true);
		} catch (JavaModelException ex) {
			return method.getElementName();
		}
	}

	/**
	 * Returns the Method index for specifierd application
	 */
	Map<String, Integer> currentIds = new HashMap<String, Integer>();
	private int getMethodId(Object element) {
		int previousInstances;
		if (!currentIds.containsKey((String)element))
			currentIds.put((String)element, 0); // If never searched this method, then seeks the first occurence
		previousInstances = currentIds.get((String)element); // to find the previousInstance-th occurence
		int i = 0;
		while (i < methods.size() && !(element.equals(methods.get(i).getElementName()) && previousInstances == 0)) {
			if (element.equals(methods.get(i).getElementName()))
				previousInstances--;
			i++;
		}
		currentIds.put((String)element, currentIds.get((String)element) + 1);
		return i;
	}

	public void addListener(ILabelProviderListener listener) {
		// TODO Auto-generated method stub
		
	}

	public void dispose() {
		// TODO Auto-generated method stub
		
	}

	public boolean isLabelProperty(Object element, String property) {
		// TODO Auto-generated method stub
		return true;
	}

	public void removeListener(ILabelProviderListener listener) {
		// TODO Auto-generated method stub
		
	}
	
}