/**
 * @author rogerstringer
 */
var pickProfileAssistantClass = null;

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

////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The contolling class
var PickprofileAssistant = Class.create ({
	
	profileListModel: {
		'listTitle': $L("Pick Profiles"),
		'items': [], // establish a default value
	},
		
	profileListAttributes: {
		listTemplate: 'pickprofile/pickprofile-header', // container or wrapper for the list
		itemTemplate: 'pickprofile/pickprofile-details', // definition of each item in the list
		swipeToDelete: false,
		autoconfirmDelete: false,
		fixedHeightItems: false,
	},	

	
	profileMenuModel: {
		items: [
			{label: $L('Help...'), command: 'help'},
		],
	},

	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. */
	  pickProfileAssistantClass = this;
	  this.levelClass = param;
	},

	setup: function() {

		this.controller.setupWidget('profileExportList', this.profileListAttributes, this.profileListModel);
		
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.profileMenuModel);

	},
	
	activate: function(event) {

		Mojo.Log.info ("activate(): PickProfile");
		/* 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('profileExportList').observe(Mojo.Event.listTap, this.handleListTap.bindAsEventListener(this));
		this.profileListModel.items = profileStore.getProfileList(false);
		this.controller.modelChanged(this.profileListModel);
	},
	
	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.controller.get('profileExportList').stopObserving(Mojo.Event.listTap, this.handleListTap);
	},

	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 */
	},
	
	handleListTap: function (event) {
		var that = this;
		if (event.item && event.item.name) {
			var name = event.item.name;
			var description = event.item.desc;
			Mojo.Log.info("handleListTap(): Name: " + event.item.name);
			this.controller.showAlertDialog({
				onChoose: function(value){
					if (value == 'export') {
						var bRet = profileStore.getProfileDetails(
							name, 
							function(details) { // onSuccess
								Mojo.Log.info("handleProfileListTap(): " + Object.toJSON(details));
								that.exportProfileFile (name, description, details);
							}, 
							function(result){ // onFailure
								that.showDialogBox ($L("Error"), "<b>Couldn't export profile.<b><br><br>"
									+ (!result || !result.errorText ? "" : result.errorText));
							}
						);

					}
				},
				title: $L("Confirmation"),
				message: "Please confirm export of profile:<br>" + event.item.desc 
					+ "<br><br>File will be stored as <b>profile-" + event.item.name + ".json</b> in the USB drive area of the device",
				allowHTMLMessage: true,
				choices: [
					{label: $L('Export'),	value: 'export', type: 'affirmative'},
					{label: $L('Cancel'),	value: 'cancel', type: 'dismiss'},
				]
			});

		} else {
			Mojo.Log.info("handleListTap(): " + Object.toJSON(event));
		}
	},

	exportProfileFile: function (myName, desc, body) { // all parameters required and must be valid
		var that = this;
		var codedSource = null;
		var source = {'description': desc, 'filename':myName, 'details': body };
		try {
			codedSource = Object.toJSON(source);
		} catch (exception) {
			Mojo.Log.logException(exception);
			this.showDialogBox ($L("Error"), "<b>Failure writing profile file.<b><br><br>Invalid data format");
			return;	
		}
		var fname = "/media/internal/profile-" + myName + ".json";
		Mojo.Log.info("exportProfileFile(): To " + fname + " : " + codedSource);
		var saveRequest = this.controller.serviceRequest(NEW_SERVICE_NAME, {
			method: 'exportjsonfile',
			parameters: {
				filename: fname,
				text: codedSource
			},
			onSuccess: function (result) {
				that.controller.cancelServiceRequest(saveRequest);
				Mojo.Log.info("exportProfileFile(): Export completed for " + myName);
				Mojo.Controller.stageController.popScene ();
			},
			onFailure: function(result) {
				that.controller.cancelServiceRequest(saveRequest);
				Mojo.Log.error("exportProfileFile(): Export error " + Object.toJSON (result));
				that.showDialogBox ($L("Error"), "<b>Failure writing profile file.<b><br><br>"
									+ (!result || !result.errorText ? "" : result.errorText));	
			}
		});

	},




	////////////////////////////////////////////////////////////////////////
	//   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");
				this.showDialogBox(null, "To export a custom log profile, simply tap on the profile. <br><br>You will be asked to confirm your selection.  Any previous saved profile with that name will be overwritten.");
			} else {
				Mojo.Log.info("handleCommand(): Command [" + event.command +  "] ignored!");
			}
		}
	},
	
	/////////////////////////////////////////////////////////////////////////
	//  Shared utilities
	/////////////////////////////////////////////////////////////////////////

	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'}]
		});
	},
	

});
