/*******************************************************************************
* 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.utils;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.stp.common.logging.LoggingProxy;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;


public class ResourceUtils {
	
	private static final LoggingProxy LOG = LoggingProxy.getlogger(ResourceUtils.class);
	   
    protected ResourceUtils() {
    }

    public static IProject getActiveProject() {
        IResource selResource = getSelectedResource();

        if (selResource != null) {
            return selResource.getProject();
        }

        return null;
    }

    public static IResource getSelectedResource() {
        // find the current page
        IWorkbenchPage page = PlatformUI.getWorkbench()
                                        .getActiveWorkbenchWindow()
                                        .getActivePage();
        IResource selResource = getSelectedResource(page);

        return selResource;
    }

    public static IResource getSelectedResource(IWorkbenchPage page) {
        IResource selResource = null;

        //the current selection in the current page
        ISelection sel = page.getSelection();
        selResource = getSelectedResource(page, sel);

        return selResource;
    }

    public static IResource getSelectedResource(IWorkbenchPage page,
        ISelection sel) {
        IResource selResource = null;

        if (sel instanceof StructuredSelection) {
            StructuredSelection ssel = (StructuredSelection)sel;
            Object element = ssel.getFirstElement();

            if (element instanceof IResource) {
                selResource = (IResource)element;
            } else if (element instanceof IAdaptable) {
                IAdaptable adaptable = (IAdaptable)element;
                selResource = (IResource)adaptable.getAdapter(IResource.class);

                if (selResource == null) {
                    IEditorPart activeEditor = page.getActiveEditor();
                    if (activeEditor != null) {
                        selResource = (IResource)activeEditor.getAdapter(IResource.class);
                    }
                }
            }
        } else if (sel instanceof TextSelection) {
            // current selection is in an editor page
            IEditorPart editor = page.getActiveEditor();
            if (editor == null) {
            	return null;
            }
            IEditorInput input = editor.getEditorInput();

            if (input instanceof IFileEditorInput) {
                selResource = ((IFileEditorInput)input).getFile();
            }
        }

        return selResource;
    }

    public static String getFileNameWithoutExt(IPath filePath) {
        String path = filePath.toOSString();
        String fileName = path.substring(path.lastIndexOf(File.separator) + 1,
                path.length());
        int idx = fileName.indexOf(".");

        if (idx >= 0) {
            return fileName.substring(0, idx);
        } else {
            return fileName;
        }
    }
    
    public static void  selectAndOpenResource(final IFile resource) {
		final IWorkbenchPage activePage= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		if (activePage != null) {
			final Display display= Display.getCurrent();
			if (display != null) {
				display.asyncExec(new Runnable() {
					public void run() {
						try {
							BasicNewResourceWizard.selectAndReveal(resource, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
							IEditorPart editor = IDE.openEditor(activePage, resource, true);
							if(editor != null && editor.isDirty())
							{
								editor.doSave(null);
							}
						} catch (PartInitException e) {
							LOG.error(e);
						}
					}
				});
			}
		}
	}
    
	public static IFile getFileFromPath(String path){
		IFile rtnValue = null;
		try{
			if(path != null && path.length() > 0){
				IWorkspace workspace = ResourcesPlugin.getWorkspace();
				IPath workspacePath = workspace.getRoot().getLocation();
				
				//change local file system path to workspace relative path 
				if (path.startsWith(workspacePath.toOSString())){
					path = path.substring(workspacePath.toOSString().length());
					
				}else if(path.startsWith(workspacePath.toString())){
					path = path.substring(workspacePath.toString().length());
				}
				IPath newPath = new Path(path);
				rtnValue = workspace.getRoot().getFile(newPath);
				if(rtnValue == null){
					rtnValue = workspace.getRoot().getFileForLocation(newPath);
				}
			}
		}catch (Exception e){
			rtnValue = null;
			LOG.debug(e);
		}

		return rtnValue;
	}

}
