package jp.ac.kyutech.ai.ylab.shiva.nativecapable.plugin;

import java.util.Iterator;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;

public class Utils {

	/**
	 * Converts the given selection into a form usable by the viewer, where the
	 * elements are resources.
	 */
	public static IResource getSelectedResource(ISelection selection) {
		IResource resource = null;

		if (selection instanceof IStructuredSelection) {
			IStructuredSelection ssel = (IStructuredSelection) selection;
			for (Iterator<?> i = ssel.iterator(); i.hasNext();) {
				Object o = i.next();
				if (o instanceof IResource) {
					resource = (IResource) o;
				} else {
					if (o instanceof IAdaptable) {
						resource = (IResource) ((IAdaptable) o)
								.getAdapter(IResource.class);
					}
				}
			}
		}
		return resource;
	}

}
