
import java.util.LinkedList;
import java.net.URL;

/**
 * <code>PageHistory</code> wraps up a <code>Collection</code> used for
 * keeping track of browsed URLs. The history will at most extend backwards
 * to 20 addresses.
 *
 * @author Pekka Ryynänen
 * @see Azure
 */
public class PageHistory {

    private LinkedList history; // browsed URLs
    private int marker;         // marks the location within history

    /**
     * Constructs an empty <code>PageHistory</code>.
     */
    public PageHistory() {
	history = new LinkedList();
    }

    /**
     * Adds the given <code>URL</code> to the traveled path.
     * If the current location is not at the newest entry - meaning
     * the path divides - then all entries after the current one
     * are forgotten and the new <code>URL</code> turns the path
     * into a new direction at that point. If the history is longer
     * than 20 entries, it is trimmed to twenty URLs.
     *
     * @param newURL the URL that is the new location within history
     */
    public void newEntry(URL newURL) {
	if (marker > 0) {
	    for (int i = 0; i < marker; i++) {
		history.removeFirst();
	    }
	    marker = 0;
	}
	history.addFirst(newURL);
	if (history.size() > 20)
	    history.removeLast();
    }

    /**
     * Takes one step back within the history and returns the <code>URL</code>
     * of the earlier page to be browsed.
     *
     * @return the URL browsed before current one, or the current one
     *         again if there are none before it
     */
    public URL goBack() {
	if ((marker + 1) < history.size())
	    marker++;
	URL oldURL = (URL)history.get(marker);
	return oldURL;
    }

    /**
     * Takes one step forward within the history and returns the <code>URL
     * </code> of the later page to be browsed.
     *
     * @return the URL browsed after current one, or the current one
     *         again if there are none after it
     */
    public URL goForward() {
	if (marker > 0)
	    marker--;
	URL oldURL = (URL)history.get(marker);
	return oldURL;
    }

    /**
     * Tells if current location within the history has none before it.
     *
     * @return <code>true</code> if at earliest entry, otherwise
     *         <code>false</code>
     */
    public boolean atOldestEntry() {
	if ((marker + 1) == history.size())
	    return true;
	else
	    return false;
    }

    /**
     * Tells if current location within the history has none after it.
     *
     * @return <code>true</code> if at latest entry, otherwise
     *         <code>false</code>
     */
    public boolean atNewestEntry() {
	if (marker == 0)
	    return true;
	else
	    return false;
    }

}

