package xmp_eventLoop;

import java.util.Deque;
import java.util.LinkedList;

public class EventLoop {
	static EventLoop EVENTLOOP;
	Deque<Runnable> eventQue;
	boolean requestedExit;

	public EventLoop() {
		eventQue = new LinkedList<Runnable>();
		requestedExit=false;
	}
	
	public void requestExit() {
		requestedExit=true;
	}
	
	public static void invokeLater(Runnable bootStrap) {
		System.out.println("EventLoop invokeLater has been called");
		EVENTLOOP=new EventLoop();
		EVENTLOOP.addEvent(bootStrap);
		EVENTLOOP.runEventLoop();
		System.out.println("EventLoop invokeLater is complete.");
	}
	
	public void runEventLoop() {
		System.out.println("EventLoop runEventLoop about to run the event loop");
		while(!requestedExit) {
			if (!eventQue.isEmpty()) {
				Runnable event=eventQue.poll();
				System.out.println("Event: " + event + " removed from the head of the event que and run");
				event.run();
			}
		}
		System.out.println("EventLoop runEventLoop finished... an exit was requested.");
	}
	
	public void addEvent(Runnable event) {
		System.out.println("EventLoop Event: " + event + " added to the tail of the event que");
		eventQue.addLast(event);
	}

}
