/**
 * 
 */
package org.ajax4jsf.event;

import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;

import javax.faces.event.FacesEvent;

/**
 * Very simple implementation of FIFO buffer, to organize JSF events queue.
 * @author asmirnov
 *
 */
public class EventsQueue  {
	
	private QueueElement first;
	
	private QueueElement last;

	/**
	 * Remove and return first queued event.
	 * @return faces event form top of queue
	 * @throws NoSuchElementException , if queue is empty.
	 */
	public FacesEvent remove() throws NoSuchElementException {
		if(isEmpty()){
			throw new NoSuchElementException("Events queue is empty");
		}
		FacesEvent element = first.getElement();
		first = first.getPrevisious();
		if(null == first){
			last = null;
		}
		return element;
	}

	/**
	 * Add event to queue.
	 * @param element
	 */
	public void add(FacesEvent element) {
		QueueElement queueElement = new QueueElement(element);
		if(isEmpty()){
			first = last = queueElement;
		} else {
			last.setPrevisious(queueElement);
			last = queueElement;
		}
	}

	public void clear() {
		first = last = null;
	}

	public boolean isEmpty() {		
		return null == first;
	}

	private static class QueueElement {
		
		private QueueElement previsious;
		
		private FacesEvent element;

		public QueueElement(FacesEvent element) {
			this.element = element;
		}

		
		/**
		 * @param previsious the previsious to set
		 */
		public void setPrevisious(QueueElement previsious) {
			this.previsious = previsious;
		}


		/**
		 * @return the previsious
		 */
		public QueueElement getPrevisious() {
			return previsious;
		}

		/**
		 * @return the element
		 */
		public FacesEvent getElement() {
			return element;
		}
		
	}
}
