/*******************************************************************************
 * 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.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.lib.explorer.LibraryExplorerTreeViewPage;
import org.eclipse.birt.report.model.api.LibraryHandle;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.IStructuredSelection;

/**
 * 
 */

public class DeleteLibraryAction extends Action
{

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

	private static final String BUNDLE_PROTOCOL = "bundleresource://"; //$NON-NLS-1$

	public DeleteLibraryAction( LibraryExplorerTreeViewPage page )
	{
		super( ACTION_TEXT );
		this.viewerPage = page;
	}

	public boolean isEnabled( )
	{
		return getSelectedLibraries( ) != null;
	}

	private List getSelectedLibraries( )
	{
		if ( viewerPage.getTreeViewer( ).getSelection( ) == null
				|| viewerPage.getTreeViewer( ).getSelection( ).isEmpty( ) )
			return null;
		List libraries = new ArrayList( );
		List files = ( (IStructuredSelection) viewerPage.getTreeViewer( )
				.getSelection( ) ).toList( );
		for ( Iterator iter = files.iterator( ); iter.hasNext( ); )
		{
			Object element = (Object) iter.next( );
			if ( element instanceof LibraryHandle )
			{
				LibraryHandle library = (LibraryHandle) element;
				if ( library.getFileName( ).startsWith( BUNDLE_PROTOCOL ) )
					return null;
				libraries.add( library );
			}
			else
			{
				return null;
			}
		}
		return libraries.size( ) > 0 ? libraries : null;
	}

	public void run( )
	{
		List libraries = getSelectedLibraries( );

		for ( Iterator iter = libraries.iterator( ); iter.hasNext( ); )
		{
			Object obj = iter.next( );
			if ( obj instanceof LibraryHandle )
			{
				LibraryHandle node = (LibraryHandle) obj;
				try
				{
					File file = new File( new URL( node.getFileName( ) ).getPath( ) );
					if ( file.exists( ) )
					{
						file.delete( );
					}
				}
				catch ( Exception e )
				{
				}
			}
		}
		viewerPage.refreshRoot( );
	}

}
