/*******************************************************************************
 * 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.ui.editors.actions;

import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.birt.report.designer.internal.ui.editors.DesignerActionBarContributor;
import org.eclipse.birt.report.designer.internal.ui.extension.EditorContributorManager;
import org.eclipse.birt.report.designer.internal.ui.extension.FormPageDef;
import org.eclipse.birt.report.designer.internal.ui.extension.EditorContributorManager.EditorContributor;
import org.eclipse.birt.report.designer.ui.actions.MenuUpdateAction;
import org.eclipse.birt.report.designer.ui.actions.NoneAction;
import org.eclipse.gef.ui.actions.UpdateAction;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;

/**
 * Override the contributor for page menus
 */

public abstract class EditorsActionBarContributor extends
		DesignerActionBarContributor
{

	/**
	 * Returns the id of the editor to contribute
	 * 
	 * @return the editor id
	 */
	abstract public String getEditorId( );

	protected IMenuManager createPageMenu( )
	{
		final ArrayList updateActions = new ArrayList( );
		IMenuManager menuManager = super.createPageMenu( );
		EditorContributor editorContruContributor = EditorContributorManager.getInstance( )
				.getEditorContributor( getEditorId( ) );
		for ( int i = editorContruContributor.formPageList.size( ) - 1; i >= 0; i-- )
		{
			FormPageDef page = editorContruContributor.getPage( i );
			final IAction action = page.pageAction;
			if ( action instanceof UpdateAction )
			{
				updateActions.add( action );
			}
			if ( action instanceof MenuUpdateAction )
			{
				final MenuManager subMenu = new MenuManager( page.displayName );
				subMenu.add( new NoneAction( ) );
				subMenu.addMenuListener( new IMenuListener( ) {

					public void menuAboutToShow( IMenuManager manager )
					{
						( (MenuUpdateAction) action ).updateMenu( subMenu );

					}
				} );
				menuManager.insertAfter( PAGE_SET_GROUP, subMenu );
			}
			else
			{
				menuManager.insertAfter( PAGE_SET_GROUP, action );
			}
		}
		menuManager.addMenuListener( new IMenuListener( ) {

			public void menuAboutToShow( IMenuManager manager )
			{
				for ( Iterator iter = updateActions.iterator( ); iter.hasNext( ); )
				{
					( (UpdateAction) iter.next( ) ).update( );
				}
			}

		} );
		return menuManager;
	}
}
