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

Photos.Scene.Thumbs = Class.create(Photos.Scene.Scroll, Photos.Common.Opacity, {
	initialize: function($super, passedArg) {
		$super(passedArg);
		this.albumCount = 0;
		// optimized for 99 photos.
		this.firstScreenThumbCount = 15;
		this.listRenderWindow = 30;
		this.deferActivate = passedArg.deferActivate;
		this.rowsPerScreen = 4;
		this.screensRendered =
				this.listRenderWindow / this.rowsPerScreen;
	},
	
	setup: function($super) {
		this.pixelThreshold = (this.screensRendered *
					this.controller.window.innerHeight) / 3;
		// 104 pixels is grabbed from the UI
		$super(this.controller.get('images_list'), {
			itemTemplate: this.templatePrefix + 'thumbs/entry',
			swipeToDelete: false,
			reorderable: false,
			initialAverageRowHeight: 106,
			scrollThreshold: this.pixelThreshold,
			renderLimit: this.listRenderWindow,
			lookahead: 50,
			itemsCallback: this.requestImagesList.bind(this),
			onItemRendered: this.rowRendered.bind(this)
		});

		this.controller.get('thumbs_album_description').hide();

		if (this.sceneModel.showAlbumName()) {
			// TODO: similar description in fullscreen too.
			// entirely necessary or refactor?
			function updateName(text) {
				this.controller.get('thumbs_album_name').update(
					text.escapeHTML());
			}

			function updateDescription(text) {
				if (text) {
					this.controller.get('thumbs_album_description').show();
				}
				this.controller.get(
					'thumbs_album_description').update(
						text.escapeHTML());
			}

			this.sceneModel.getName(updateName.bind(this));
			this.sceneModel.getDescription(
						updateDescription.bind(this));

			this.controller.get('album_info').show();
		} else {
			this.controller.get('album_info').hide();
		}

		if (this.sceneModel.allowComments()) {
			this.controller.setupWidget(Mojo.Menu.commandMenu, {}, {
				visible: true,
				items: [{}, {
					label: $L("Comments"),
					command: 'show-comments'
				}, {}]
			});
		}

		this.controller.get('thumbs_empty_message').update(
						$L("This album is empty."));
	},

	handleCommand: function($super, event) {
		if (event && event.type === Mojo.Event.command &&
			event.command && event.command === 'show-comments') {
			this.pushWithTemplate(null, 'comments', {
				model: this.sceneModel.newCommentsModel()
			});
		} else {
			return $super(event);
		}
	},

	requestImagesList: function(widget, offset, limit) {
		// 3 row wide hack
		this.sceneModel.request(
			offset * 3,
			(this.albumCount === 0 ?
				this.firstScreenThumbCount : limit * 3),
			this.translateImageResults.bind(this, offset, limit));
	},

	activate: function($super) {
		$super();
		if (this.deferActivate) {
			delete this.deferActivate;
			AppAssistant.stageController.activate();
		}
	},

	rowRendered: function(widget, model, node) {
		// 3 row wide hack
		this.doLoader(model.imagePath1, model.imageRealPath1,
						model.rowCount, 0, node);
		this.doLoader(model.imagePath2, model.imageRealPath2,
						model.rowCount, 1, node);
		this.doLoader(model.imagePath3, model.imageRealPath3,
						model.rowCount, 2, node);
	},

	doLoader: function(path, realPath, row, maskIndex, rowNode) {
		if (!realPath) {
			return;
		}

		if (this.sceneModel.useRowRequester()) {
			this.rowRequester.load(row, this.loadImage.bind(
				this, path, realPath, rowNode,
				rowNode.down(".image-mask", maskIndex)));
		} else {
			this.loadImage(path, realPath, rowNode,
				rowNode.down(".image-mask", maskIndex),
				function (){});
		}
	},

	loadImage: function(path, fullPath, rowNode, maskNode, complete) {
		if (!rowNode.parentNode) {
			//Mojo.Log.info("Removed node before load!");
			complete();
			return;
		} else if (maskNode.down(".image-src").getStyle(
			"backgroundImage") == "url(\"" + path + "\")") {
			//Mojo.Log.info("Already loaded this image.");
			complete();
			return;
		}
//		Mojo.Log.error("Loading img ", path, fullPath);
		var image = this.controller.document.createElement("img");
		image.onload = this.imageDone.bind(
				this, maskNode, image, complete);
		image.onerror = this.retryImageNoThumbnail.bind(
				this, maskNode, image, fullPath, complete);
		image.src = path;
	},

	imageDone: function($super, element, image, complete) {
		// set background image of thumbnail div
		var sourceDiv = element.down(".image-src");
		sourceDiv.setStyle({
			backgroundImage: "url(\"" + image.src + "\")"
		});
		
		// stretching the image to fill the 90x90 thumbnail size
		if (image.width < 90 || image.height < 90) {
			if (image.width < image.height) {
				sourceDiv.addClassName("portrait");
			} else {
				sourceDiv.addClassName("landscape");
			}
		}
		
		sourceDiv.sourceImage = image.src;
		$super(element, image, complete);
	},

	handleSelection: function(event) {
		var targetRow = this.controller.get(
					event.originalEvent.down.target);

		if (!targetRow.hasClassName('single-item')) {
			targetRow = targetRow.up('div.single-item');
		}

		if (!targetRow) {
			return;
		}
		// TODO: 3 row wide hack.
		var realOffset = (event.index * 3) +
				targetRow.previousSiblings().length;
		if (realOffset >= this.albumCount) {
			return;
		}

		targetRow.addClassName("selected");
		this.pushWithTemplate(event, {
			name: 'fullscreen',
			disableSceneScroller: true
		}, {
			model: this.sceneModel.newFullscreenModel(
				realOffset,
				targetRow.down(".image-src").sourceImage)
		});
	},

	translateImageResults: function(offset, limit, images, imagesTotal) {
		var i = 0;
		var sofar = 0;
		var list = [];
		var prefix = this.params.applicationRoot ?
			(this.params.applicationRoot + "/") : "";

		// 3 row wide hack
		while (i < images.length) {
			var superImage = {prefix: prefix};
			if (images[i]) {
				superImage.imageRealPath1 = images[i].imagePath;
				superImage.imagePath1 = images[i].thumb;
			}
			
			if (images[i + 1]) {
				superImage.imageRealPath2 =
						images[i + 1].imagePath;
				superImage.imagePath2 = images[i + 1].thumb;
				superImage.imageVisibleClass2 = "single-item";
			} else {
				// add css display:none
				superImage.imageVisibleClass2 =
							"single-item-hidden";
			}
			
			if (images[i + 2]) {
				superImage.imageRealPath3 =
						images[i + 2].imagePath;
				superImage.imagePath3 = images[i + 2].thumb;
				superImage.imageVisibleClass3 = "single-item";
			} else {
				// add css display:none
				superImage.imageVisibleClass3 =
							"single-item-hidden";
			}
			
			superImage.rowCount = offset + (i / 3);
			i += 3;
			list[sofar] = superImage;
			sofar++;
		}
		
		if (this.albumCount !== imagesTotal) {
			this.albumCount = imagesTotal;
			this.controller.get('thumb_count').update(
				$L("#{total}").interpolate({
					total: this.albumCount
			}));
		}

		var total = Math.ceil(this.albumCount / 3);
		Mojo.Log.info("this result set contained: " + sofar);
		Mojo.Log.info("we supplied a grand total of: " + total);

		this.mainListElement.mojo.noticeUpdatedItems(offset, list);
		this.rowRequester.doWork(
			this.firstScreenThumbCount, this.ready.bind(this));
		this.mainListElement.mojo.setLength(total);

		this.controller.get('no-thumbs-div').style.display =
			(this.albumCount === 0) ? 'block' : 'none';
	}
});

