package de.cooperateproject.ui.nature;

import org.apache.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;

public class ProjectOpenedListener implements IResourceChangeListener {

	private static final Logger LOGGER = Logger.getLogger(ProjectOpenedListener.class);

	@Override
	public void resourceChanged(IResourceChangeEvent event) {
		if (event == null || event.getDelta() == null) {
			return;
		}
		try {
			event.getDelta().accept(new IResourceDeltaVisitor() {
				public boolean visit(final IResourceDelta delta) throws CoreException {
					if (isRelevantForClean(delta)) {
						IProject project = (IProject) delta.getResource();
						Job rebuild = new Job("rebuild") {
							@Override
							protected IStatus run(IProgressMonitor monitor) {
								try {
									project.build(IncrementalProjectBuilder.CLEAN_BUILD, null);
								} catch (CoreException e) {
									LOGGER.error("Exception during rebuild after opening or closing of a project", e);
									return Status.CANCEL_STATUS;
								}
								return Status.OK_STATUS;
							}
						};
						rebuild.schedule();
					}

					return true;
				}
			});
		} catch (CoreException e) {
			LOGGER.error("Exception during rebuild after opening or closing of a project", e);
		}
	}

	private static boolean isRelevantForClean(IResourceDelta delta) {
		if ((delta.getResource().getType() & IResource.PROJECT) == 0) {
			return false;
		}
		
		if (delta.getKind() == IResourceDelta.CHANGED && (delta.getFlags() & IResourceDelta.OPEN) != 0) {
			return true;
		}
		
		if (delta.getKind() == IResourceDelta.REMOVED) {
			return true;
		}
		
		return false;
	}
	
}

@@ -658,16 +658,84 @@
 s.Job;%0A%0A
+import de.cooperateproject.ui.nature.tasks.BackgroundTasksAdapter;%0A%0A
 public c
@@ -1716,16 +1716,189 @@
 %09%09%09%09%09%7D%0A%0A
+%09%09%09%09%09if (isRelevantForDelete(delta)) %7B%0A%09%09%09%09%09%09IProject project = (IProject) delta.getResource();%0A%09%09%09%09%09%09BackgroundTasksAdapter.getManager().deregisterProject(project);%0A%09%09%09%09%09%7D%0A
 %09%09%09%09%09ret
@@ -2316,32 +2316,211 @@
 rn true;%0A%09%09%7D%0A%09%09%0A
+%09%09return false;%0A%09%7D%0A%09%0A%09private static boolean isRelevantForDelete(IResourceDelta delta) %7B%0A%09%09if ((delta.getResource().getType() & IResource.PROJECT) == 0) %7B%0A%09%09%09return false;%0A%09%09%7D%0A%09%09%0A
 %09%09if (delta.getK

Stop background tasks when project is removed.