/*******************************************************************************
 * 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.lib.explorer.action;

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

import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.model.api.LibraryHandle;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;

/**
 * Remove external library from library explorer.
 * @deprecated
 */

public class RemoveLibraryAction extends Action
{

	private StructuredViewer viewer;

	private static final String ACTION_TEXT = Messages.getString( "RemoveLibraryAction.Text" ); //$NON-NLS-1$

	public RemoveLibraryAction( StructuredViewer viewer )
	{
		super( ACTION_TEXT );
		this.viewer = viewer;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.action.Action#isEnabled()
	 */
	public boolean isEnabled( )
	{
		LibraryHandle library = getSelectedLibrary( );
		if ( library != null )
		{
			String[] libraries = ReportPlugin.getDefault( )
					.getLibraryPreference( );
			return isArrayContain( libraries, library.getFileName( ) );
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.action.Action#run()
	 */
	public void run( )
	{
		LibraryHandle library = getSelectedLibrary( );
		if ( library != null )
		{
			String[] libraries = ReportPlugin.getDefault( )
					.getLibraryPreference( );
			ReportPlugin.getDefault( )
					.setLibraryPreference( removeElementFromArray( libraries,
							library.getFileName( ) ) );
		}
	}

	private LibraryHandle getSelectedLibrary( )
	{
		IStructuredSelection selection = (IStructuredSelection) viewer.getSelection( );
		if ( selection != null && selection.size( ) == 1 )
		{
			if ( selection.getFirstElement( ) instanceof LibraryHandle )
			{
				return (LibraryHandle) selection.getFirstElement( );
			}
		}
		return null;
	}

	private String[] removeElementFromArray( String[] array, String element )
	{
		List result = new ArrayList( array.length );
		for ( int i = 0; i < array.length; i++ )
		{
			if ( !array[i].equals( element ) )
				result.add( array[i] );
		}
		return (String[]) result.toArray( new String[result.size( )] );
	}

	private boolean isArrayContain( String[] array, String element )
	{
		for ( int i = 0; i < array.length; i++ )
		{
			if ( array[i].equals( element ) )
				return true;
		}
		return false;
	}
}
