package usda.weru.util;

import java.awt.EventQueue;
import java.lang.reflect.InvocationTargetException;
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();
    }

    /**
     *
     * @param r
     */
    public synchronized void execute(final Runnable r) {
        c_tasks.offer(new Runnable() {

            @Override
            public void run() {
                try {
                    EventQueue.invokeAndWait(r);
                } catch (InterruptedException | InvocationTargetException e) {
                    //do something with e here
                    //TODO
                } 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;
    }

    /**
     *
     * @param runnable
     */
    public static final void invokeLater(Runnable runnable) {
        instance().execute(runnable);
    }

}
