import java.io.*;
import java.util.*;
import java.net.*;


public class urlmonitor {
	protected ArrayList<LinkedList> PriorityUrl;
	protected LinkedList<String> urlqueue = new LinkedList<String>();
	protected HashSet<String> urls = new HashSet<String>(); //list of urls we have already visited
	protected int urlsize = 0, processed = 0,limit;
	protected boolean debug = true;

	public urlmonitor(int levels){
		PriorityUrl = new ArrayList<LinkedList>(levels);
		for(int i =0; i < levels; i++){
			PriorityUrl.add(new LinkedList<String>());
		}
	}

	public synchronized void addurl(String myurl, int ulevel){
		boolean bolNotify = false;
		//make sure we haven't already seen this url
		if(!urls.contains(myurl)){
			if(isEmpty()){
				bolNotify = true;
			}
			LinkedList temp = PriorityUrl.get(ulevel);
			temp.add(myurl);
			urls.add(myurl);
			urlsize++;
			if(bolNotify){
				notifyAll();
			}
			if(isFull()){
				waitnow();
			}
		}
	}
	public synchronized String geturl(){
		boolean bolNotify = false;
		if(!isEmpty()){
			if(isFull()){
				bolNotify = true;
			}
			Iterator itr = PriorityUrl.listIterator();
			while(itr.hasNext()){
				LinkedList temp = (LinkedList)itr.next();
				if(!temp.isEmpty()){
					urlsize--;
					String strTemp = (String)temp.removeFirst();
					if(bolNotify){
						notify();
					}
					return strTemp;
				}
			}
		}
		//else if it is empty wait
		waitnow();
		return null;

	}

	private void waitnow(){
		try{wait();}catch(InterruptedException e){};
	}
	public synchronized boolean isFull(){
		if(urlsize > 1000){
			return true;
		}else{
			return false;
		}
	}
	public synchronized boolean isEmpty(){
		Iterator itr = PriorityUrl.listIterator();
		while(itr.hasNext()){
			LinkedList temp = (LinkedList)itr.next();
			if(!temp.isEmpty()){
				return false;
			}
		}
		return true;
	}
	public synchronized void printurls(){
		Iterator itr = PriorityUrl.listIterator();
		while(itr.hasNext()){
			LinkedList temp = (LinkedList)itr.next();
			Iterator itru = temp.listIterator();
			while(itru.hasNext()){
				System.out.println(itru.next());
			}
		}

	}
	public synchronized boolean dbug(){
		return debug;
	}

	public synchronized void toggledbug(){
		if(debug == true){
			debug = false;
		}else{
			debug = true;
		}
	}

}