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

/**
 * A collection of history items all of which were visited on the same
 * day (but not same time).
 */
HistoryDay = Class.create({

	/**
	 * Constructor.
	 */
	initialize: function(date) {
		/**
		 * The date (but not the time) for which all of these UrlReference's
		 * are on. We only look at the year/month/day of this value.
		 */
		this.date = date;

		/**
		 * An array of UrlReference instances.
		 */
		this.items = $A();
	},

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

	/**
	 * Does this date (just the date portion) match the supplied date?
	 *
	 * @return true if matches, false if not.
	 */
	matchesDate: function(date) {
		return (this.date.getFullYear() === date.getFullYear()) &&
				(this.date.getMonth() === date.getMonth()) &&
				(this.date.getDate() === date.getDate());
	},

	/**
	 * Finds a history item for the specified url.
	 *
	 * @return The UrlReference or undefined if not found.
	 */
	findItem: function(url) {

		for (var i = 0; i < this.items.length; i++) {
			var item = this.items[i];
			if (item.urlEquals(url)) {
				return item;
			}
		}

		return undefined;
	},

	/**
	 * Add the UrlReference to this day. The caller has already verified
	 * that the day of the item matches this day.
	 *
	 * A URL will only exist in the same day once. The last time the page was
	 * visited is the date/time that it is given. So if the same URL is added
	 * a second time then only the date is updated in the URL already in
	 * this list.
	 */
	addItem: function(item) {
		var found = this.findItem(item.url);
		if (Object.isUndefined(found)) {
			// Add a new history item.
			this.items[this.items.length] = item;
		}
		else {
			// Just update the date
			if (item.date > found.date) {
				found.date = item.date;
			}
		}
		this.items.sort(this.sortItemCallback);
	},

	addNewItem: function(item) {
		// Add a new history item.
		this.items[this.items.length] = item;
		this.items.sort(this.sortItemCallback);
	}
});
