/*******************************************************************************
* Copyright (c) 2006 IONA Technologies PLC
* 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:
*     IONA Technologies PLC - initial API and implementation
*******************************************************************************/
package org.eclipse.stp.sc.common.actions;


import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;


public abstract class CreateActionBase implements IObjectActionDelegate, IWorkbenchWindowActionDelegate {
    protected IStructuredSelection selection;
    
    static final String JAVA_EDITOR_ID = "org.eclipse.jdt.ui.CompilationUnitEditor";
    

    public void init(IWorkbenchWindow window) {
        // TODO Auto-generated method stub
    }
    
    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        // TODO Auto-generated method stub
    }


    public void selectionChanged(IAction action, ISelection sel) {
        if (sel == null) {
            selection = null;
        } else if (sel instanceof IStructuredSelection) {
            selection = (IStructuredSelection)sel;
        }
    }
    
    
    protected boolean isJavaEditorOpen(IResource javaResource) {
        if (javaResource == null) {
            return false;
        }

        IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        int editorCount = activePage.findEditors(new FileEditorInput((IFile)(javaResource)),
                                                 JAVA_EDITOR_ID,
                                                 IWorkbenchPage.MATCH_INPUT 
                                                     | IWorkbenchPage.MATCH_ID).length;
        return editorCount > 0;
    }
    
    protected void openJavaEditor(IResource javaResource) throws PartInitException {
        if (javaResource == null) {
            return;
        }

        IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        activePage.openEditor(new FileEditorInput((IFile)(javaResource)), JAVA_EDITOR_ID, true);
    }

}
