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

Photos.Model.FacebookComments = Class.create(Photos.Model.Comments, {
	initialize: function($super, previewUrl, title, caption,
					accountID, albumID, photoID) {
		if (accountID === undefined ||
			(albumID === undefined && photoID === undefined)) {
			throw "Invalid parameters to new FacebookComments()";
		}
		$super(previewUrl, title, caption);
		this.accountID = accountID;
		this.albumID = albumID;
		this.photoID = photoID;
	},

	cancelCommentsRequest: function() {
		if (this.commentsRequest) {
			this.commentsRequest.cancel();
			delete this.commentsRequest;
		}
	},

	request: function(offset, limit, done) {
		function gotComments(reply) {
			Mojo.Log.info("comments reply " + Object.toJSON(reply));
			delete this.commentsRequest;
			if (!reply || !reply.comments ||
						!reply.comments.comments) {
				Mojo.Log.error("Failed to get photo comments.");
				done([], 0, !!reply.comments.canComment);
				return;
			}

			var comments = reply.comments.comments || [];
			for (var c = 0, len = comments.length; c < len; c++) {
				var comment = comments[c];
				comment.readableDate = Mojo.Format.formatDate(
					new Date(comment.created * 1000),
					"short");
			}
			done(comments, comments.length,
				!!reply.comments.canComment);
		}

		Mojo.Log.info("making comments request " +
						Object.toJSON(this.photoID));
		this.cancelCommentsRequest();
		var params = this.photoID ?
			{pids: [this.photoID]} : {aid: this.albumID}
		params.accountTag = this.accountID;
		this.commentsRequest = this.controller.serviceRequest(
			'palm://com.palm.photo.facebook', {
				method: 'getPhotoComments',
				onSuccess: gotComments.bind(this),
				onFailure: gotComments.bind(this),
				parameters: params
		});
	},

	postComment: function(message, done) {
		function commentAdded(reply) {
			Mojo.Log.info("comment add reply " +
							Object.toJSON(reply));
			done(!!reply.returnValue);
		}

		var params = (this.photoID ?
				{pid: this.photoID} : {aid: this.albumID});
		params.accountTag = this.accountID;
		params.comment = message;
		this.controller.serviceRequest(
			'palm://com.palm.photo.facebook', {
			method: 'addPhotoComment',
			onSuccess: commentAdded.bind(this),
			onFailure: commentAdded.bind(this),
			parameters: params
		});
	}
});

