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

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

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

	
	//Create the attributes for the textfield
	descAttributes: {
		hintText: 'Profile description',
		focus: true,
		enterSubmits: true,
		multiline: true,
		modelProperty: 'originalValue',
		modifierState: Mojo.Widget.sentenceCase,
		focusMode: Mojo.Widget.focusInsertMode,
		requiresEnterKey: false,
		changeOnKeyPress: true,
	},
	
	//Create the model for the text field
	descModel: {
		'originalValue' : '',
		'disabled'      : false
	},
	
	profileMenuModel: {
		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'},
		],
	},

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

	setup: function() {
		this.controller.setupWidget('profile_desc', this.descAttributes, this.descModel);
		
//		this.controller.setupWidget('profileList', this.profileListAttributes, this.profileListModel);
		
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.profileMenuModel);

	},
	
	activate: function(event) {
		this.controller.get('profile_desc').observe(Mojo.Event.propertyChange, this.descriptionChanged.bind(this));
		Mojo.Log.info ("activate(): Profile");
		this.descModel.originalValue = "";
		this.controller.modelChanged(this.descModel);
		/* 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('profile_button').observe(Mojo.Event.tap, this.createProfile.bindAsEventListener(this));
//		this.controller.get('profileList').observe(Mojo.Event.listTap, this.handleListTap.bindAsEventListener(this));
// 		this.controller.get('profileList').observe(Mojo.Event.listDelete, this.handleListDelete.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('profile_button').stopObserving(Mojo.Event.tap, this.createProfile);
//		this.controller.get('profileList').stopObserving(Mojo.Event.listTap, this.handleListTap);
// 		this.controller.get('profileList').stopObserving(Mojo.Event.listDelete, this.handleListDelete);
		this.controller.get('profile_desc').stopObserving(Mojo.Event.propertyChange, this.descriptionChanged);
	},

	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) {
//		if (event.item && event.item.name) {
//			Mojo.Log.info("handleListTap(): Name: " + event.item.name);
//		} else Mojo.Log.info("handleListTap(): " + Object.toJSON (event));
//	},

//	handleListDelete: function (event) {
//		if (event.item && event.item.name) {
//			Mojo.Log.info("handleListDelete(): Name: " + event.item.name);
//			profileStore.deleteProfile (event.item.name);
//		} else Mojo.Log.info("handleListDelete(): " + Object.toJSON (event));
//	},
	
	descriptionChanged: function (event) {
		this.descModel.originalValue = event.value;	
	},

	createProfile: function(event){
		$('profile_desc').blur();
		Mojo.Log.info("createProfile(): Description: " + this.descModel.originalValue);
		 //Show an alert with the error.
		if (this.descModel.originalValue == "") {
			$('profile_desc').focus();
			this.showDialogBox(null, $L("<b>Please enter a description of the profile!</b>"));
		} else {
			var msg = profileStore.verifyNewDescription(this.descModel.originalValue);
			if (null != msg) {
				$('profile_desc').focus();
				Mojo.Log.info("createProfile(): " + msg);
				this.showDialogBox (null, "<b>" + msg + "</b>");
			} else {
				this.createDateProfile().bind(this).defer();
			}
		}
	},

	createDateProfile: function(){
		var that = this;
		var desc = that.descModel.originalValue;
		Mojo.Log.info("createDateProfile():");
		this.controller.serviceRequest('palm://com.palm.systemservice/time', {
			method: 'getSystemTime',
			onSuccess: function(result)	{
				var name = profileStore.formatDateName(result.localtime, 'T');
				Mojo.Log.info("createDateProfile(): Name: " + name);
				that.levelClass.saveProfile(name, desc, that.displayAddSuccess.bind(that));
			},
			onFailure: function(result) {
				console.log("failed");
				Mojo.Log.error("createDateProfile(): Failed");
				this.showDialogBox ($L("Error"), $L("<b>Couldn't get system date and time to create profile name.</b>"));
			}
		});
	},
	
	createNamedProfile: function(name) {
		Mojo.Log.info("createNamedProfile():" + name);
	},
	
	displayAddSuccess: function (name, description) {
		this.profileListModel.items = profileStore.getProfileList(false);
		this.controller.modelChanged(this.profileListModel);
		this.showDialogBox (null, $L("<b>New profile successfully added!</b>") 
				+ "<br><br> \"" + description + '\"',
				function() {Mojo.Controller.stageController.popScene ();});
	},


	////////////////////////////////////////////////////////////////////////
	//   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 create a custom log profile you first set the specific log levels needed, and then come back to this screen to save that collection of log levels settings as a profile."
					+ "<br><br>Remember to enter a meaningful description for new profiles!");
			} else {
				Mojo.Log.info("handleCommand(): Command [" + event.command +  "] ignored!");
			}
		}
	},
	
	/////////////////////////////////////////////////////////////////////////
	//  Shared utilities
	/////////////////////////////////////////////////////////////////////////

	showDialogBox: function (title, message, action) {
		this.controller.showAlertDialog({
			onChoose: function(value){
				if (action) action();
			},
			title: (title && title.length > 0 ? title : $L("Information")),
			message: (message ? message : ''),
			allowHTMLMessage: true,
			choices: [{label: $L('OK'),	value: 'ok', type: 'dismiss'}]
		});
	},
	

});
