// herbruikbare package

package be.hogent.h20;

class H20_ListNode {
	
	Object data;
	H20_ListNode nextNode;
	
	H20_ListNode(Object object) {
		this (object,null);
	}
	
	H20_ListNode(Object object, H20_ListNode node) {
		data = object;
		nextNode = node;
	}
	
	Object getObject() {
		return data;
	}
	
	H20_ListNode getNext() {
		return nextNode;
	}

}

public class H20_List {
	
	private H20_ListNode firstNode;
	private H20_ListNode lastNode;
	private String name;
	
	public H20_List() {
		this("Lijst");
	}
	
	public H20_List(String listName) {
		name = listName;
		firstNode = lastNode = null;
	}
	
	public synchronized void insertAtFront(Object insertItem) {
		if (isEmpty())
			firstNode = lastNode = new H20_ListNode(insertItem);
		else
			firstNode = new H20_ListNode(insertItem, firstNode);
	}
	
	public synchronized void insertAtBack(Object insertItem) {
		if (isEmpty())
			firstNode = lastNode = new H20_ListNode(insertItem);
		else
			lastNode = lastNode.nextNode = new H20_ListNode(insertItem);
	}
	
	public synchronized Object removeFromFront() throws H20_EmptyListException {
		if (isEmpty())
			throw new H20_EmptyListException(name);
		
		Object removedItem = firstNode.data;
		
		if (firstNode == lastNode)
			firstNode = lastNode = null;
		else
			firstNode = firstNode.nextNode;
		
		return removedItem;
	}
	
	public synchronized Object removeFromBack() throws H20_EmptyListException {
		if (isEmpty())
			throw new H20_EmptyListException(name);
		
		Object removedItem = lastNode.data;
		
		if (firstNode == lastNode)
			firstNode = lastNode = null;
		else {
			H20_ListNode current = firstNode;
			
			while (current.nextNode != lastNode)
				current = current.nextNode;
			
			lastNode = current;
			current.nextNode = null;
		}
		
		return removedItem;
		
	}
	
	public synchronized boolean isEmpty() {
		return firstNode == null;
	}
	
	public synchronized void print() {
		if (isEmpty()) {
			System.out.println(name + " is leeg.");
			return;
		}
		
		System.out.print("De " + name + " bevat: ");
		H20_ListNode current = firstNode;
		
		while (current != null) {
			System.out.print(current.data.toString() + " ");
			current = current.nextNode;
		}
		
		System.out.println("\n");
	}
}
