/*******************************************************************************
 * Copyright (c) 2013 Pivotal Software, Inc.
 * 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:
 * Pivotal Software, Inc. - initial API and implementation
 *******************************************************************************/
package org.springsource.ide.eclipse.commons.livexp.core;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.progress.UIJob;

/**
 * This class should be used instead of ValueListener when the code it
 * wants to execute upon receiving a 'gotValue' event is required
 * to run in the UIThread (i.e. typically this is code that needs to
 * update or read widgets in the UI).
 */
public abstract class UIValueListener<T> implements ValueListener<T> {
	
	private class NotifyingJob extends UIJob {
		
		LiveExpression<T> exp;
		
		public NotifyingJob(LiveExpression<T> exp) {
			super("Notifying Job");
			this.exp = exp;
			setSystem(true);
		}

		@Override
		public IStatus runInUIThread(IProgressMonitor monitor) {
			uiGotValue(exp, exp.getValue());
			return Status.OK_STATUS;
		}
		
	}

	private NotifyingJob job = null;
	
	/**
	 * This method is final. Implement 'uiGotValue' instead.
	 */
	public final void gotValue(final LiveExpression<T> exp, final T value) {
		NotifyingJob job = this.job;
		if (job == null || job.exp != exp) {
			job = new NotifyingJob(exp);
			this.job = job;
		}
		job.schedule();
	}

	/**
	 * Subclasses should implement. This method will always be called in the UIThread.
	 */
	protected abstract void uiGotValue(LiveExpression<T> exp, T value);

}

@@ -1078,18 +1078,17 @@
 er%3CT%3E %7B%0A
-%09
 %0A
+
 %09private
@@ -1123,19 +1123,17 @@
 UIJob %7B%0A
-%09%09
 %0A
+
 %09%09LiveEx
@@ -1149,19 +1149,17 @@
 T%3E exp;%0A
-%09%09
 %0A
+
 %09%09public
@@ -1411,11 +1411,9 @@
 %09%09%7D%0A
-%09%09
 %0A
+
 %09%7D%0A%0A
@@ -1450,10 +1450,9 @@
 ll;%0A
-%09
 %0A
+
 %09/**
@@ -1830,16 +1830,16 @@
 d.%0A%09 */%0A
-
 %09protect
@@ -1900,10 +1900,298 @@
 alue);%0A%0A
+%09/**%0A%09 * A Lambda-friendly way to creat %7B@link UIValueListener%7D%0A%09 */%0A%09public static %3CT%3E UIValueListener%3CT%3E from(ValueListener%3CT%3E l) %7B%0A%09%09return new UIValueListener%3CT%3E() %7B%0A%09%09%09@Override%0A%09%09%09protected void uiGotValue(LiveExpression%3CT%3E exp, T value) %7B%0A%09%09%09%09l.gotValue(exp, value);%0A%09%09%09%7D%0A%09%09%7D;%0A%09%7D%0A%0A
 %7D%0A

Add a lamba-friendly method for creating UIValueListener