package de.ugoe.cs.swe.bnftools.utils;

import java.util.Iterator;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

public class EObjectResolver implements
		IUnitOfWork<IEObjectDescription, XtextResource> {
	private IResourceDescriptions resourceDescriptions;
	private EObject element;

	public EObjectResolver(EObject element,
			IResourceDescriptions resourceDescriptions) {
		this.element = element;
		this.resourceDescriptions = resourceDescriptions;
	}

	public IEObjectDescription exec(XtextResource state) throws Exception {
		if (element != null) {
			final URI eObjectURI = EcoreUtil.getURI(element);
			IResourceDescription resourceDescription = resourceDescriptions
					.getResourceDescription(eObjectURI.trimFragment());
			if (resourceDescription != null) {
				Iterator<IEObjectDescription> eObjectDescriptions = Iterables
						.filter(resourceDescription.getExportedObjects(),
								new Predicate<IEObjectDescription>() {
									public boolean apply(
											IEObjectDescription input) {
										return input.getEObjectURI().equals(
												eObjectURI);
									}
								}).iterator();
				if (eObjectDescriptions.hasNext()) {
					return eObjectDescriptions.next();
				}
			}
		}
		return null;
	}
}