/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation.
 * 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:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

package org.eclipse.birt.report.designer.internal.ui.editors.script;

import java.util.Iterator;

import org.eclipse.birt.report.designer.internal.ui.editors.script.JSObjectMetaData.JSMethod;
import org.eclipse.birt.report.model.api.metadata.IArgumentInfo;
import org.eclipse.birt.report.model.api.metadata.IArgumentInfoList;
import org.eclipse.birt.report.model.api.metadata.IClassInfo;
import org.eclipse.birt.report.model.api.metadata.IMethodInfo;

class EngineClassMethod implements JSMethod, Comparable
{

	private IMethodInfo method;
	private String displayText;
	private IClassInfo classInfo;

	public EngineClassMethod( IMethodInfo method, IClassInfo classInfo )
	{
		this.method = method;
		this.classInfo = classInfo;
	}

	public String getName( )
	{
		return method.getDisplayName( );
	}

	public JSObjectMetaData getReturn( )
	{
		JSObjectMetaData meta = JSSyntaxContext.getEnginJSObject( method
				.getReturnType( ) );
		if ( meta == null )
			try
			{
				return JSSyntaxContext
						.getJavaClassMeta( method.getReturnType( ) );
			}
			catch ( ClassNotFoundException e )
			{
				return null;
			}
		return meta;
	}

	public String getDisplayText( )
	{
		if ( displayText == null )
		{
			StringBuffer strbuf = new StringBuffer( getName( ) );
			strbuf.append( "(" ); //$NON-NLS-1$
			for ( Iterator iter = method.argumentListIterator( ); iter
					.hasNext( ); )
			{
				IArgumentInfoList element = (IArgumentInfoList) iter.next( );
				int i = 0;
				for ( Iterator iterator = element.argumentsIterator( ); iterator
						.hasNext( ); )
				{
					if ( i++ > 0 )
					{
						strbuf.append( ", " ); //$NON-NLS-1$
					}
					IArgumentInfo argument = (IArgumentInfo) iterator.next( );
					strbuf.append( argument.getType( ) ).append( " " ) //$NON-NLS-1$
							.append( argument.getName( ) );
				}
				break;
			}
			strbuf.append( ") " ); //$NON-NLS-1$
			strbuf.append( classInfo.getName( ) );
			displayText = strbuf.toString( );
			strbuf = null;
		}
		return displayText;
	}

	public String getDescription( )
	{
		return null;
	}

	public int getVisibility( )
	{
		if ( method.isStatic( ) )
			return EngineClassJSObject.VISIBILITY_STATIC;
		return 0;
	}

	public int compareTo( Object obj )
	{
		if ( obj instanceof EngineClassMethod
				&& ( (EngineClassMethod) obj ).getName( ) != null )
		{
			return getName( ).compareToIgnoreCase(
					( (EngineClassMethod) obj ).getName( ) );
		}
		return 0;
	}

}
