/*
 * Copyright 2008-2009 Palm, Inc. All rights reserved.
 */

/**
 * This represents the entire browser history.
 */
HistoryList = Class.create({

	MAX_HISTORY_DAYS: 21,

	/**
	 * Constructor.
	 */
	initialize: function() {
		this.days = $A();
	},

	/**
	 * Find the HistoryDay instance (if there is one) for the
	 * specified date.
	 *
	 * @return Reference to the HistoryDay object, or undefined if not found.
	 */
	findDay: function(date) {

		for (var i = 0; i < this.days.length; i++) {
			var day = this.days[i];
			if (day.matchesDate(date)) {
				return day;
			}
		}

		return undefined;
	},

	/**
	 * Remove the history that is old that we don't care about anymore.
	 */
	trimOldHistory: function() {
		while (this.days.length > this.MAX_HISTORY_DAYS) {
			this.days.pop();
		}
	},

	/**
	 * A callback to Array.sort for sorting items by date.
	 */
	sortDayCallback: function(dayA, dayB) {
		if ( dayA.date > dayB.date ) {
			return -1;
		}
		else if ( dayA.date < dayB.date ) {
			return 1;
		}
		else {
			return 0;
		}
	},

	/**
	 * Sort the days reverse chronological order.
	 */
	sort: function() {
		this.days.sort(this.sortDayCallback);
	},

	/**
	 * Add a page to the history. Days will be sorted but Will not trim off old history.
	 */
	addPage: function(url, title, date) {
		if (Object.isNumber(date)) {
			var utc = date;
			date = new Date();
			date.setUTCTime(utc);
		}
		var day = this.findDay(date);
		if (Object.isUndefined(day)) {
			// Start a new day
			var dayDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());	// date, but not time
			day = new HistoryDay(dayDate);
			this.days.push(day);
			this.sort();
		}
		day.addItem(new UrlReference(url, title, date));
	},

	addNewPage: function(url, title, date) {
		if (Object.isNumber(date)) {
			var utc = date;
			date = new Date();
			date.setUTCTime(utc);
		}
		var day = this.findDay(date);
		if (Object.isUndefined(day)) {
			// Start a new day
			var dayDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());	// date, but not time
			day = new HistoryDay(dayDate);
			this.days.push(day);
			this.sort();
		}
		day.addNewItem(new UrlReference(url, title, date));
	}
});
