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

/**
 * The data source for the history list (BigList).
 */
HistoryDataSource = Class.create({

	histModel: undefined,

	/**
	 * Constructor.
	 */
	initialize : function(histModel) {
		this.histModel = histModel;

		this.createItems();

		if (this.controller) {
			this.controller.dataAddedAtEnd.bind(this.controller).delay(0.2, this.items.length);
		}
	},

	createItems: function() {

		this.items = $A();
		this.limit = this.offset = 0;

		var prevDate = new Date(0);
		var visible;

		for (var d = 0; d < this.histModel.days.length; d++) {
			var day = this.histModel.days[d];
			for (var i = 0; i < day.items.length; i++) {
				var item = day.items[i];
				if ( this.datesMatch(prevDate, item.date )) {
					visible = "visibility: hidden; height:0";
				}
				else {
					visible = "visibility: visible";
				}
				var hdr = item.date.toLocaleString();
				this.items.push({title:item.title, url:item.url, 'hdr-visible':visible, hdr:hdr});
				prevDate = item.date;
			}
		}

		if (this.items.length === 0) {
			visible = "visibility: hidden; height:0";
			this.items.push({title:"Empty", url:"", 'hdr-visible':visible, hdr:""});
		}
	},

	datesMatch: function(date1, date2) {
		return (date1.getFullYear() === date2.getFullYear()) &&
				(date1.getMonth() === date2.getMonth()) &&
				(date1.getDate() === date2.getDate());
	},

	updateOffsetAndLimit: function(offset, limit) {
	    this.offset = offset;
	    this.limit = limit;
	    this.sendNewData();
	},

	dataAsResultSet: function() {
		var lastIndex = this.offset + this.limit;
		if (lastIndex > this.items.length) {
			lastIndex = this.items.length;
		}
		var offset = this.offset;
		if (offset > this.items.length) {
			offset = this.items.length;
		}
		var resultSet = {
			offset: offset,
			limit: lastIndex,
			list: this.items.slice(offset, lastIndex),
			total: this.items.length};
		var itemIndex = offset + 1;
		resultSet.list.each(function(item) {item.index = itemIndex;++itemIndex;});
		return resultSet;
	},

	sendNewData: function() {
		if (this.controller && this.controller.handleNewData) {
			var resultSet = this.dataAsResultSet();
			this.controller.handleNewData.bind(this.controller).delay(0.2, resultSet);
		}
	}
});

