/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package usda.weru.util;

import java.awt.EventQueue;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 *
 * @author Joseph Levin <joelevin@weru.ksu.edu>
 */
public class ExceptionEventQueue {

    private static ExceptionEventQueue c_instance;
    final Queue<Runnable> c_tasks = new ArrayDeque<Runnable>();
    final Executor c_executor;
    Runnable active;

    private ExceptionEventQueue() {
        c_executor = Executors.newSingleThreadExecutor();
    }

    public synchronized void execute(final Runnable r) {
        c_tasks.offer(new Runnable() {

            public void run() {
                try {
                    EventQueue.invokeAndWait(r);

                } 
                catch(Exception e){
                    //do something with e here
                }
                finally {
                    scheduleNext();
                }
            }
        });
        if (active == null) {
            scheduleNext();
        }
    }

    protected synchronized void scheduleNext() {
        if ((active = c_tasks.poll()) != null) {
            c_executor.execute(active);
        }
    }

    private static synchronized ExceptionEventQueue instance(){
        if(c_instance == null){
            c_instance = new ExceptionEventQueue();
        }
        return c_instance;
    }

    public static final void invokeLater(Runnable runnable){
        instance().execute(runnable);
    }

}
