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

/**
 * The assistant for the browser page scene.
 */
function CustomizeiconAssistant( params ) {
	this.urlReference = params.urlReference;
}

/**
 * Setup this scene.
 */
CustomizeiconAssistant.prototype.setup = function() {

    try {
        this._setupWebView();
    } 
    catch (e) {
        Mojo.Log.logException(e, 'CustomizeiconAssistant#setup');
    }
};
	
CustomizeiconAssistant.prototype.cleanup = function() {
};


CustomizeiconAssistant.prototype.activate = function() {
    try {
        var webView = this.controller.get('icon_web_view');
		this.controller.get('saveIconButton').addEventListener(Mojo.Event.tap, this.handleSaveIcon.bindAsEventListener(this));
	  } 
    catch (e) {
        Mojo.Log.logException(e, 'activate');
    }
	this.d = this.controller.document.querySelector('div[x-mojo-element=_Dialog]');
	this.d.hide();

};

CustomizeiconAssistant.prototype.deactivate = function() {
	if (this.d) {
		this.d.show();
		if (this.urlReference.tmpIconFile64) {
			var img = Mojo.View.render({object: {icon: this.urlReference.tmpIconFile64}, template: "bookmarks/imageicondiventry"});
			this.controller.get('imageicondiv').update(img);
		}
	}
};

/**
 * Setup the web view.
 */
CustomizeiconAssistant.prototype._setupWebView = function() {
	var params = { cacheAdapter: false };	// Caching uses too much memory.
	params.url = this.urlReference.url;
	this.controller.setupWidget('icon_web_view', params);
};

CustomizeiconAssistant.prototype.handleSaveIcon = function(){

	try {
		var webView = this.controller.get('icon_web_view');
		
		var now = Date.now(); // To create unique filename.
		webView.mojo.saveViewToFile(CustomizeiconAssistant.tmpCaptureFile);
		if (this.urlReference.tmpIconFile64 !== this.urlReference.iconFile64) {
			webView.mojo.deleteImage(this.urlReference.tmpIconFile64); // Delete old temp 64x64 pixel image
		}
	
		var frame =  this.controller.get('frame');
		var frameDim = frame.getDimensions();

		var frameLeft = parseInt(frame.getStyle('left'), 10);
		var frameTop = parseInt(frame.getStyle('top'), 10);

		this.urlReference.tmpIconFile64 = CustomizeiconAssistant.createBrowserImageName('icon64', now);
		webView.mojo.generateIconFromFile(CustomizeiconAssistant.tmpCaptureFile, this.urlReference.tmpIconFile64, 
			frameLeft, frameTop, frameLeft + frameDim.width, frameTop + frameDim.height);
	
		if (this.urlReference.tmpIconFile32 !== this.urlReference.iconFile32) {
			webView.mojo.deleteImage(this.urlReference.tmpIconFile32); // Delete old temp 32x32 pixel image
		}

		var scenePos = this.controller.getSceneScroller().mojo.getScrollPosition();
		frameLeft = -scenePos.left;
		frameTop = -scenePos.top;
		webView.mojo.saveViewToFile(CustomizeiconAssistant.tmpCaptureFile,
				frameLeft, frameTop, frameLeft + frameDim.width, frameTop + frameDim.height);
		
		this.urlReference.tmpIconFile32 = CustomizeiconAssistant.createBrowserImageName('icon32', now);
		webView.mojo.resizeImage(CustomizeiconAssistant.tmpCaptureFile, this.urlReference.tmpIconFile32, 32, 32);
		this.controller.stageController.popScene({
			type: 'customizeicon'
		});
	} 
	catch (e) {
		var that = this;
		Mojo.Log.logException(e);
		this.controller.showAlertDialog({
			onChoose: function(value){
				that.controller.stageController.popScene({
					type: 'customizeicon'
				});
			},
			title: $L("Error"),
			message: $L("Failed to save icon: ") + e.message,
			choices: [{
				label: $L('Done'),
				value: 'dismiss',
				type: 'alert'
			}]
		});
	}
};

/**
 * Create the full filename for a browser image.
 * 
 * @param {String} basename	A basename for the file. Usually 'icon' or 'thumbnail'
 * @param {String} unique A unique filename differntiator like a random number, etc.
 */
CustomizeiconAssistant.createBrowserImageName = function(basename, unique) {
	// If you change this directory then make sure to change the 
	// desktop-binaries installation for the simulator.
	return '/var/luna/data/browser/icons/' + basename + '-' + unique + '.png';
};

/**
 * handle a menu command.
 */
CustomizeiconAssistant.prototype.handleCommand = function(event) {
	
	try {
		switch (event.type) {
		
		case Mojo.Event.command:
				
			if (event.command === Mojo.Menu.helpCmd) {
				this._showHelpCommand();
			}
			break;
			
		case Mojo.Event.commandEnable:
			
			// Standard Application Menu commands.
			if (event.command === Mojo.Menu.helpCmd) {
				
				event.stopPropagation(); // Enable the chosen menuitems
				
			} 				
			break;
		}
	} 
	catch (e) {
		Mojo.Log.logException(e, 'handleCommand');
	}
};

CustomizeiconAssistant.prototype._showHelpCommand = function() {
	
	// Launch the help system.
	AppAssistant.launchHelp();
};

CustomizeiconAssistant.tmpCaptureFile = '/tmp/BrowserTempCapture.png';
CustomizeiconAssistant.kIconCropRectWidth  = 128;	// Must match GUI
CustomizeiconAssistant.kIconCropRectHeight = 128;	// Must match GUI

