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

/**
 * Constructor.
 * 
 * If this is a new UrlReference then the tmpIconFile* images will be set and the iconFile* images will not.
 * Conversely if the iconFile* images are set and the tmpIconFile* are not then this is an existing bookmark
 * that will be edited.
 * 
 * <ul>
 * <li>sceneController - Instance of Mojo.Controller.SceneController.</li>
 * <li>bookmarkStore - Instance of BookmarkStore.</li>
 * <li>urlReference - Instance of UrlReference.</li>
 * <li>task - String (BookmarkDialogAssistant.createBookmarkTask, BookmarkDialogAssistant.editBookmarkTask,
 *                   or BookmarkDialogAssistant.createLaunchpointTask.</li>
 * <li>deleteImage - function to call to delete an image.</li>
 * <li>onClose - function to call when closing the bookmark dialog.</li>
 * </ul>
 * 
 * @param {Object} The assistant parameters. 
 */
function BookmarkDialogAssistant(params) {
	
	this.params = Mojo.Model.decorate(params);
	
	Mojo.assert(params.deleteImage, "Must provide image delete func.");
	
	this.savedUrlReference = false;

	this.tempFiles = $A();
	switch (this.params.task) {
		case BookmarkDialogAssistant.createBookmarkTask:
			this.actionBtnTitle = $L('Add bookmark');
			break;
		case BookmarkDialogAssistant.editBookmarkTask:
			this.actionBtnTitle = $L('Save bookmark');
			break;
		case BookmarkDialogAssistant.createLaunchpointTask:
			this.actionBtnTitle = $L('Add to Launcher');
			break;
		default:
			this.actionBtnTitle = $L('Save');
	}
	var urlReference = this.params.urlReference;
	if (urlReference.tmpIconFile64 === undefined) {
		urlReference.tmpIconFile64 = urlReference.iconFile64;
	}
	if (urlReference.tmpIconFile32 === undefined) {
		urlReference.tmpIconFile32 = urlReference.iconFile32;
	}
}

BookmarkDialogAssistant.createBookmarkTask = 'task-create-bookmark';
BookmarkDialogAssistant.editBookmarkTask = 'task-edit-bookmark';
BookmarkDialogAssistant.createLaunchpointTask = 'task-create-launchpoint';


BookmarkDialogAssistant.prototype.setup = function(widget) {
	
	var controller = this.params.sceneController;
	this.widget = widget;
	
	// A change to the default behaviour of textfields means
	// we have to set the changeOnKeyPress attribute to 'true'
	// to guarantee we have the model updated with the textfield
	// entry on each keypress.
	var titleFieldAttributes = { 
		modelProperty: 'title',
		changeOnKeyPress: true,
		focusMode: Mojo.Widget.focusSelectMode  
	};
	controller.setupWidget('titleField', titleFieldAttributes, this.params.urlReference);
	
	var urlFieldAttributes = {
		modelProperty: 'url', 
		textReplacement:false, 
		changeOnKeyPress: true,
		focusMode: Mojo.Widget.focusSelectMode  
	};
	controller.setupWidget('urlField', urlFieldAttributes, this.params.urlReference);

	var img = Mojo.View.render({object: {icon: this.params.urlReference.tmpIconFile64}, template: "bookmarks/imageicondiventry"});
	controller.get('imageicondiv').update(img);
	// if (this.params.task !== BookmarkDialogAssistant.createLaunchpointTask) {
	// 	controller.get('pageiconsubtitle').hide();
	// }
	if (this.params.task === BookmarkDialogAssistant.createLaunchpointTask) {
		controller.get('actionButton').addEventListener(Mojo.Event.tap, this._onAddLaunchpointButtonTap.bindAsEventListener(this));
	}
	else {
		controller.get('actionButton').addEventListener(Mojo.Event.tap, this._onAddBookmarkButtonTap.bindAsEventListener(this));
	}
	controller.get('cancelBookmarkButton').addEventListener(Mojo.Event.tap, this._onCancelButtonTap.bindAsEventListener(this));
	controller.listen('imageicondiv', Mojo.Event.tap, this._onCustomizeIconButtonTap.bindAsEventListener(this));
};

BookmarkDialogAssistant.prototype._onCustomizeIconButtonTap = function() {
	this.params.sceneController.stageController.pushScene('customizeicon', {urlReference: this.params.urlReference});
};

/** @private */
BookmarkDialogAssistant.prototype._addLaunchIconSuccess = function(response) {

};

/** @private */
BookmarkDialogAssistant.prototype._addLaunchIconFailure = function() {
    Mojo.Log.error("Failed to add launch icon");
};

/** @private */
BookmarkDialogAssistant.prototype._onBookmarkAddSuccess = function(oldIconFile64, oldIconFile32) {
    
	// Delete the old icons that are no longer referenced in the database
	if (oldIconFile64) {
		this.params.deleteImage(oldIconFile64);
	}
	if (oldIconFile32) {
		this.params.deleteImage(oldIconFile32);
	}
};

BookmarkDialogAssistant.prototype._onAddBookmarkButtonTap = function() {
	if (this.params.urlReference.url !== undefined) {
		var oldIconFile64 = this.params.urlReference.iconFile64;
		var oldIconFile32 = this.params.urlReference.iconFile32;
		this.params.urlReference.iconFile64 = this.params.urlReference.tmpIconFile64;
		this.params.urlReference.iconFile32 = this.params.urlReference.tmpIconFile32;
		this.params.bookmarkStore.insertOrUpdateBookmark( this.params.urlReference, 
			this._onBookmarkAddSuccess.bind(this, oldIconFile64, oldIconFile32),
			function(sqlFunc, params) {
				Mojo.Log.error("ERROR adding/updating bookmark, code: %s, message '%s'", 
					params.code, params.message);
			}
		);
		this.savedUrlReference = true;
	}
	else {
		Mojo.Log.warn("No current URL");
	}

	if (this.params.onClose) {
		this.params.onClose(this.savedUrlReference);
		delete this.params.onClose;
	}
		
	this.widget.mojo.close();
};

BookmarkDialogAssistant.prototype._onAddLaunchpointButtonTap = function() {
    try {
        var appParams = {
            scene: 'page',
            url: this.params.urlReference.url
        };

        var title = this.title || $L('Web page');
        var callParams = {
            id: 'com.palm.app.browser',
            'icon': this.params.urlReference.tmpIconFile64,
            'title': this.params.urlReference.title,
            'params': appParams
        };
        this.params.sceneController.serviceRequest('palm://com.palm.applicationManager/addLaunchPoint', {
            parameters: callParams,
            onSuccess: this._addLaunchIconSuccess.bind(this),
            onFailure: this._addLaunchIconFailure.bind(this)
        });
		this.savedUrlReference = true;
    } 
    catch (e) {
        Mojo.Log.logException(e, '_onAddLaunchpointButtonTap');
    }

	if (this.params.onClose) {
		this.params.onClose(this.savedUrlReference);
		delete this.params.onClose;
	}
	
	this.widget.mojo.close();
};

BookmarkDialogAssistant.prototype._onCancelButtonTap = function() {
	if (this.params.urlReference.iconFile64 !== this.params.urlReference.tmpIconFile64) {
		this.params.deleteImage(this.params.urlReference.tmpIconFile64);
	}
	if (this.params.urlReference.iconFile32 !== this.params.urlReference.tmpIconFile32) {
		this.params.deleteImage(this.params.urlReference.tmpIconFile32);
	}
	if (this.params.task !== BookmarkDialogAssistant.editBookmarkTask) {
		this.params.deleteImage(this.params.urlReference.thumbnailFile);
	}

	if (this.params.onClose) {
		this.params.onClose(this.savedUrlReference);
		delete this.params.onClose;
	}
	this.widget.mojo.close();
};

BookmarkDialogAssistant.prototype.cleanup = function() {
	
	// If the callback hasn't been called then call it. This
	// was probably due to a back.
	if (this.params.onClose) {
		this.params.onClose(false);
	}	
};

/**
 * Display the bookmark dialog.
 *
 * @param {Object} An object containing parameters for this function. See BookmarkDialogAssistant constructor.
 */
BookmarkDialogAssistant.showDialog = function(params) {

	var assistant = new BookmarkDialogAssistant(params);
	var title = params.urlReference.title || '';	
	
	return params.sceneController.showDialog({
		template: 'bookmarks/bookmark-dialog',
		assistant: assistant,
		title: title,
		// We do this flag for the moment to give the user
		// the expect behaviour of dropping back to the
		// bookmark/launcher dialog after using the customize
		// icon feature.
		preventCancel: true,
		actionBtnTitle: assistant.actionBtnTitle
	});
};
