/**
 * @author rogerstringer
 */
var logAssistantClass = null;
var doingLogCreation  = false; // used for create & clear to prevent issues caused by double-tap on buttons 

// constants
var filenamePattern   = /[^a-zA-Z0-9_#-]/;
var NEW_SERVICE_NAME  = "palm://com.palm.logctld";

////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The contolling class
var LogAssistant = Class.create ({
	
	lastLogName: null,
	lastLogDesc: null,
	
	//Create the attributes for the textfield
	filenameAttributes: {
		hintText: 'Log name (optional)',
		focus: true,
		enterSubmits: true,
		multiline: false,
		modelProperty: 'originalValue',
		modifierState: Mojo.Widget.sentenceCase,
		focusMode: Mojo.Widget.focusInsertMode,
		requiresEnterKey: true,
		label: 'Log Name'
	},
	
		//Create the model for the text field
	filenameModel: {
		'originalValue' : ''
	},

	createLogReq: {},
	
	attributes: {
		modifierState: Mojo.Widget.sentenceCase,
		focusMode: Mojo.Widget.focusInsertMode,
		requiresEnterKey: true
	},
	
	//Create the attributes for the textfield
	descAttributes: {
		hintText: 'Issue description',
		focus: true,
		enterSubmits: true,
		multiline: true,
		modelProperty: 'originalValue',
		modifierState: Mojo.Widget.sentenceCase,
		focusMode: Mojo.Widget.focusInsertMode,
		requiresEnterKey: true,
	},
	
	//Create the model for the text field
	descModel: {
		'originalValue' : ''
	},
	
	//progress spinner
    spinnerAttrs: {
        property: 'spinningP'
    },
    
    spinnerModel: {
        spinningP: false
    },

	setQuickLog: false,
	
	initialize: function(param) {
	/* this is the creator function for your scene assistant object. It will be passed all the 
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below. */
	  logAssistantClass = this;
	  this.setQuickLog = (!param || param != 'quick' ? false : true);
	},

	setup: function() {

		this.logMenuModel = {
			items: [
				{
					label:$L('Edit'), 
					items: [
						{label:$L('Cut'), command:Mojo.Menu.cutCmd, shortcut:'x', disabled:false},
	                	{label:$L('Copy'), command:Mojo.Menu.copyCmd, shortcut:'c', disabled:false}, 
	                	{label:$L('Paste'), command:Mojo.Menu.pasteCmd, shortcut:'v', disabled:false}
					]
				},                
				{label: $L('Help...'), command: 'help'}
			],
		};
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.logMenuModel);


		this.controller.setupWidget('log_name', this.filenameAttributes, this.filenameModel);
		this.controller.setupWidget('log_desc', this.descAttributes, this.descModel);
    	this.controller.setupWidget('log-spinner', this.spinnerAttrs, this.spinnerModel);
		

		if (!this.lastLogName) { // get from cookie, perhaps?
			$('log_email_button').style.display = 'none';
			var memCookie = new Mojo.Model.Cookie("com.palm.app.collectlogs");
			if (memCookie) {
				var result = memCookie.get();
				if (!result || !result.name) {
					Mojo.Log.info("setup(): No cookie found!");
					//$('log_progress_label').innerHTML = "No cookie settings found!";
				} else {
					//$('log_progress_label').innerHTML = "[" + result.name + "] [" + result.description + "]";
					if (result.name) {
						var d = (!result.description ? "" : decodeURI(result.description));
						Mojo.Log.info("setup(): verify file exists: " + result.name);
						this.verifyFileExists (result.name, d);
					} else {Mojo.Log.info("setup(): Cookie present but empty");}
				}
			}

		} else {
			Mojo.Log.info("setup(): display email button");
			$('log_email_button').style.display = (PalmSystem.isMinimal === true ? 'none' : 'inline');
		}

 		if (this.setQuickLog == true) {$('log_button').style.display = 'none';	}
		else  {$('log_button').style.display = 'inline';}
	},
	
	
	activate: function(event) {
		// Support quick log file
		if (this.setQuickLog == true) {
			this.descModel.originalValue = "";
			this.setQuickLog = false; // return to default value
			this.createDateLog();
		}
		/* put in event handlers here that should only be in effect when this scene is active. For
		   example, key handlers that are observing the document */
		this.controller.get('log_button').observe(Mojo.Event.tap, this.createLog.bindAsEventListener(this));
		this.controller.get('log_email_button').observe(Mojo.Event.tap, this.emailLog.bindAsEventListener(this));
	},
	
	deactivate: function(event) {
		/* remove any event handlers you added in activate and do any other cleanup that should happen before
		   this scene is popped or another scene is pushed on top */
		 this.setQuickLog = false; // return to default value
		 $('log_button').style.display = 'inline';
		this.controller.get('log_button').stopObserving(Mojo.Event.tap, this.createLog);
		this.controller.get('log_email_button').stopObserving(Mojo.Event.tap, this.emailLog);

	},

	cleanup: function(event) {
		/* this function should do any cleanup needed before the scene is destroyed as 
		   a result of being popped off the scene stack */
	},
	

	createLog: function(event){
		 //Show an alert with the error.
		$('log_name').blur();
		$('log_desc').blur();
		this.createLogContinue.bind(this).defer();
	},
	
	createLogContinue: function(event){
		if (this.descModel.originalValue == "") {
			$('log_desc').focus();
			this.showDialogBox(null, $L("<b>Please enter a description of the issue!</b>"));
		} else if (this.filenameModel.originalValue == "") {
			//this.createLogDispatch("default");
			var that = this;
			Mojo.Log.info ("createLogContinue(): Filename is empty!");
			this.controller.showAlertDialog({
				onChoose: function(value){
				},
				title: $L("Confirmation"),
				message: $L("<b>Log name is empty!</b><br><br>Do you want the system to create a unique name from date and time?"),
				allowHTMLMessage: true,
				choices: [
					{label: $L('Create dated name'),value: 'ok',type: 'affirmative'},
					{label: $L('Cancel'),value: 'cancel',type: 'dismiss'}
				],
				onChoose: function(value){
					if (value === 'ok') {
						that.createDateLog();
					}
					else {
						$('log_name').focus();
					}
				},
			});

		}
		else {
			var isBadChars = filenamePattern.test(this.filenameModel.originalValue);
			if (false == isBadChars) {
				this.createLogDispatch(this.filenameModel.originalValue);
			} else {
				$('log_name').focus();
				this.showDialogBox ($L("Error"), $L("<b>Log name contains invalid characters!</b><br><br>Please just use alphabetic and numeric characters, plus hyphen, underscore and # characters."));
			}
		}
	},
	
	createDateLog: function(event){
		var that = this;
		//$('log_name').blur();
		if (doingLogCreation == true) return;
		Mojo.Log.info("createDateLog(): ");
		that.spinOn();
		Mojo.Log.info ("createDateLog(): About to request system time");
		this.controller.serviceRequest('palm://com.palm.systemservice/time', {
			method: 'getSystemTime',
			onSuccess: function(result)		{
				Mojo.Log.info ("createDateLog(): Date/Time returned, about to format file name..." + Object.toJSON(result));
				var name = profileStore.formatDateName(result.localtime, '_');
				Mojo.Log.info("createDateLog(): date name: " + name);
				that.createLogDispatch(name);
			},
			onFailure: function(result) {
				that.spinOff();
				Mojo.Log.error ("createDateLog(): Failed to get system time");
				console.log("failed");
				this.showDialogBox ($L("Error"), $L("<b>Couldn't get system date and time to create file name.</b>"));
				
			}
		});
	},
	
	createLogDispatch: function(name) {
		var that = this;
		if (doingLogCreation == true) return;
		doingLogCreation = true;
		Mojo.Log.info("createLogDispatch(): " + name);
		$('log_button').style.display = 'none';
		$('log_progress_label').innerHTML = "Creating " + name + ".ssl.tar<br>This can take 10 - 20 secs!";
		this.spinOn();
		var saveServiceRequest = this.controller.serviceRequest(NEW_SERVICE_NAME, {
			method: 'collectall',
			parameters: {
				filename: name,
				description: encodeURI(this.descModel.originalValue),
			},
			onSuccess: function(value) {
				that.controller.cancelServiceRequest(saveServiceRequest);
				$('log_progress_label').innerHTML = "";
				that.spinOff();
				that.handleCollectLogsOK(value);
			},
			onFailure: function(value) {
				that.controller.cancelServiceRequest(saveServiceRequest);
				$('log_progress_label').innerHTML = "";
				that.spinOff();
				that.handleCollectLogsError(value);
			}
		});
	},
	
	handleCollectLogsOK: function(result){
		Mojo.Log.info("handleCollectLogsOK():");
		doingLogCreation = false;
	
		var that = this;
		if (result.folder && result.filename) {
			this.lastLogName = result.folder + result.filename + ".ssl.tar";
			this.lastLogDesc = this.descModel.originalValue;
			Mojo.Log.info("handleCollectLogsOK(): display email button");
			$('log_email_button').style.display = (PalmSystem.isMinimal === true ? 'none' : 'inline');
			var memCookie = new Mojo.Model.Cookie("com.palm.app.collectlogs");
			if (memCookie) {
				memCookie.put({'name':this.lastLogName, 'description':encodeURI(this.lastLogDesc)});
			}
			var buttonChoices = [{
					label: $L('OK'),
					value: 'ok',
					type: 'dismiss'
				}];
			if (PalmSystem.isMinimal !== true) {
				buttonChoices.push ({					
					label: $L('Email Log...'),
					value: 'email',
					type: 'color'
				});
			}
			
			this.controller.showAlertDialog({
				onChoose: function(value){
					if (value == 'email') {
						this.emailLog(null);
					}
					Mojo.Controller.stageController.popScene();
				}.bind(this),
				title: $L("Success"),
				message: "Created log dump <b>" + result.filename + ".ssl.tar" +
					"</b> in " +
					result.folder +
					"<br><br>To retrieve, plug the device into your PC/Mac.  When asked, select \"USB Drive Mode\" and look for <b>logs/" +
					result.filename +
					".ssl.tar</b> on the newly inserted drive.",
				allowHTMLMessage: true,
				choices: buttonChoices,
			});
		}
		else {
			this.handleCollectLogsError(result);
		}
	},
	
	handleCollectLogsError: function(result){
		doingLogCreation = false;
		this.controller.showAlertDialog({
			onChoose: function(value){
			},
			title: $L("Failure"),
			message: "<b>Log creation failed</b><br><br>"+ (!result.errorText ? "" : result.errorText),
			allowHTMLMessage: true,
			choices: [{
				label: $L('OK'),
				value: 'ok',
				type: 'dismiss'
			}]
		});
	},
	
	emailLog: function(event){
		if (true == doingLogCreation) {return;}
		if (!this.lastLogName) {
			this.showDialogBox($L('Information'), $L("Sorry, there is no log file to email."));
			return;
		}
		console.log("about to send email with file: " + this.lastLogName);	
		//$('log_progress_label').innerHTML = "Email: ";
		
		var params = {
			summary: 'Collect Logs Attached', 
			text: "Issue Description:<br>" + (!this.lastLogDesc || this.lastLogDesc.length == 0 ? "" : this.lastLogDesc + "<br><br>"),
			attachments: [{fullPath: this.lastLogName}]					
		};
					
		var that = this;
		this.controller.serviceRequest('palm://com.palm.applicationManager', {
			method: 'open',
			parameters: {
				//target: 'mailto:castle.collectlogs@palm.com',
				id: 'com.palm.app.email',
				params: params
			},
			onSuccess: function(result){
				$('log_progress_label').innerHTML = "";
				//that.showDialogBox($L('Information'), "<b>Email was successful!</b><br><br>" + that.lastLogName);
			},
			onFailure: function(result){
				$('log_progress_label').innerHTML = "";
				that.showDialogBox($L('Error'), "<b>Attempt to send email was unsuccessful!</b><br><br>" +
					(result && result.errorText ? result.errorText : "") );
			}
		});
	},
	
	verifyFileExists: function (name, desc) {
		var that = this;
		//$('log_progress_label').innerHTML = name;
		var saveServiceRequest = this.controller.serviceRequest(NEW_SERVICE_NAME, {
			method: 'logfileexists',
			parameters: {
				'filename': name
			},
			onSuccess: function(result) {
				that.controller.cancelServiceRequest(saveServiceRequest);
				//$('log_progress_label').innerHTML = "Success";
				that.lastLogName = name;
				that.lastLogDesc = (!desc && result.description ? decodeURI(result.description) : desc);
				if (doingLogCreation != true) {
					Mojo.Log.info("verifyFileExists(): display email button");
					$('log_email_button').style.display = (PalmSystem.isMinimal === true ? 'none' : 'inline');
					$('log_progress_label').innerHTML = "";
				}
			},
			onFailure: function(result) {
				that.controller.cancelServiceRequest(saveServiceRequest);
				//that.showDialogBox($L('Error'), "<b>Attempt to verify file was unsuccessful!</b><br><br>"
				//	+ (result && result.errorCode ? "#:" + result.errorCode + "  " : "")
				//	+ (result && result.errorText ? result.errorText : "") );

			}
		});

	},

	spinOn: function(){
	    this.spinnerModel.spinningP = true;
	    this.controller.modelChanged(this.spinnerModel);
		this.filenameModel.disabled = true;
	    this.controller.modelChanged(this.filenameModel);
		this.descModel.disabled = true;
	    this.controller.modelChanged(this.descModel);
		Mojo.Log.info("spinOn(): hide email button");
		$('log_email_button').style.display = 'none';
	},
	
	spinOff: function(){
	    this.spinnerModel.spinningP = false;
	    this.controller.modelChanged(this.spinnerModel);
		this.filenameModel.disabled = false;
	    this.controller.modelChanged(this.filenameModel);
		this.descModel.disabled = false;
	    this.controller.modelChanged(this.descModel);
		Mojo.Log.info("spinOff(): email button " + (this.lastLogName == null ? 'hidden' : 'shown'));
		$('log_email_button').style.display = (this.lastLogName == null ? 'none' : 'inline');		
		$('log_button').style.display = (PalmSystem.isMinimal === true ? 'none' : 'inline');
	},


	////////////////////////////////////////////////////////////////////////
	//   Handle command method, which currently just services the main menu
	////////////////////////////////////////////////////////////////////////

 	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if (event.command == 'help') {
				Mojo.Log.info("handleCommand(): help");
			} else {
				Mojo.Log.info("handleCommand(): Command [" + event.command +  "] ignored!");
			}
		}
	},
	
	/////////////////////////////////////////////////////////////////////////
	//
	/////////////////////////////////////////////////////////////////////////
	
	showDialogBox: function (title, message) {
		this.controller.showAlertDialog({
			onChoose: function(value){
			},
			title: (title && title.length > 0 ? title : $L("Information")),
			message: (message ? message : ''),
			allowHTMLMessage: true,
			choices: [{label: $L('OK'),	value: 'ok', type: 'dismiss'}]
		});
	},
	
	clearLastLogName: function () {
		this.lastLogName = null;
	},

});
