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

var PoundDataBrowserAssistant = Class.create({
	
	initialize: function(divId) {
		
		this.divId = divId;
		TelephonyCommands.dataExtFieldsQuery(this.dataExtFieldsQueryDone.bind(this));
	
	},
	
	primFieldMap: $H({pringgip: "NGG", pringgport : "Port", pringgsecport: "Secure Port"}),
	secFieldMap: $H({secnggip: "NGG", secnggport : "Port", secnggsecport: "Secure Port"}),
	mmgFieldMap: $H({mmgip: "MMG IP", mmgport : "MMG Port", mmgbuffersize: "Buffer Size",mmgtimeout:"Time Out"}),
	
	setup: function() {
		
		// Model to use for the command menu.
		this.cmdMenuBrowserModel = {
			items: [{}, {}, {}, {}]};
		// Set up view menu with scene header
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, this.cmdMenuBrowserModel);
		
		this.browserPrimListModel = {
            items: PoundData.poundDataPrimExtList			
        };
		
		this.browserSecListModel = {
            items: PoundData.poundDataSecExtList			
        };
		
		this.mmgListModel = {
            items: PoundData.poundDataMMGList			
        };
		
		this.mmscurlListModel = {
            items: PoundData.poundDataMMSCList			
        };
		
		this.template = {
			itemTemplate: 'poundDataBrowser/listitem',            		          
        };		
					
        this.controller.setupWidget('primngg', this.template, this.browserPrimListModel);
		Mojo.Event.listen(this.controller.get('primngg'), Mojo.Event.propertyChange, this.primListChangeHandler.bindAsEventListener(this));
		Mojo.Event.listen(this.controller.get('primngg'), Mojo.Event.listTap, this.verifyMSL.bindAsEventListener(this,'primngg'));
		
		this.controller.setupWidget('secngg', this.template, this.browserSecListModel);
		Mojo.Event.listen(this.controller.get('secngg'), Mojo.Event.propertyChange, this.secListChangeHandler.bindAsEventListener(this));
		Mojo.Event.listen(this.controller.get('secngg'), Mojo.Event.listTap, this.verifyMSL.bindAsEventListener(this,'secngg'));	
		
		this.controller.setupWidget('mmg', this.template, this.mmgListModel);
		Mojo.Event.listen(this.controller.get('mmg'), Mojo.Event.propertyChange, this.mmgListChangeHandler.bindAsEventListener(this));
		Mojo.Event.listen(this.controller.get('mmg'), Mojo.Event.listTap, this.verifyMSL.bindAsEventListener(this,'mmg'));			
		
		this.controller.setupWidget('mmscurl', this.template, this.mmscurlListModel);
		Mojo.Event.listen(this.controller.get('mmscurl'), Mojo.Event.propertyChange, this.mmscurlChangeHandler.bindAsEventListener(this));
		
		Mojo.Event.listen(this.controller.get('mmscurl'), Mojo.Event.listTap, this.mmscEdit.bindAsEventListener(this));
		
		this.textAttributes = {
			enterSubmits: true,
			focus: false,
			multiline: false,       
			textCase: Mojo.Widget.steModeLowerCase,
			focusMode: Mojo.Widget.focusSelectMode,
			maxLength: 40,
			modelProperty: "FIELDVALUE",
			disabledProperty: 'DISABLED',
		};		
		
		this.controller.setupWidget('datafield', this.textAttributes, {});
		this.controller.get('header').innerHTML = this.divId;
		this.controller.get(this.divId).show();
	},
	
	mmscEdit: function(event) {
		// CASE: use carrier validation for MMSC URL
		if ( Mojo.Controller.getAppController().assistant.useCarrierVerificationMMSCURL ) {
			this.showCarrierAuthDialog(function() {
				(function() {
					this.verifyMSL(event,'mmscurl');
				}).bind(this).delay(1);
			}.bind(this));
		// CASE: use MSL validation for MMSC URL
		} else {
			this.verifyMSL(event,'mmscurl');
		}
	},
	
	cleanup: function() {
		this.controller.commitChanges();
				
		PoundData.poundDataPrimExtList.clear();
		PoundData.poundDataSecExtList.clear();
		PoundData.poundDataMMGList.clear();
		PoundData.poundDataMMSCList.clear();
	},
		
	showError: function() {
		this.controller.showAlertDialog({
	    	onChoose: function(value) {},
		    message: "One of the field value is missing!",
		    choices:[
	        {label: 'Close', value:'dismissed', type:'color'}    
		    ]
		  });
	},
	
	dataExtFieldsQueryDone: function(success, status, dataInfo) {
		if(!dataInfo)
			return;
			
		if (success) {
			var fields = $H(dataInfo);
			
			this.primFieldMap.each(function(pair) {
				var obj = new Object();
				obj.FIELDNAME = pair.value;
				obj.FIELDVALUE = fields.get(pair.key);
				if(PoundData.mslVerified) 
					obj.DISABLED = false;
				else
					obj.DISABLED = true;
				PoundData.poundDataPrimExtList.push(obj);
			}.bind(this));
			
			this.secFieldMap.each(function(pair) {
				var obj = new Object();
				obj.FIELDNAME = pair.value;
				obj.FIELDVALUE = fields.get(pair.key);
				if(PoundData.mslVerified) 
					obj.DISABLED = false;
				else
					obj.DISABLED = true;
				PoundData.poundDataSecExtList.push(obj);
			}.bind(this));
						
			// single-line MMSC URL
			PoundData.poundDataMMSCList.push({
				FIELDNAME: "",
				FIELDVALUE: fields.get('mmscurl'),
				DISABLED: ! PoundData.mslVerified
			});
			//this.controller.get('mmscurlvalue').innerHTML = fields.get('mmscurl');
			
			this.mmgFieldMap.each(function(pair) {
				var obj = new Object();
				obj.FIELDNAME = pair.value;
				obj.FIELDVALUE = fields.get(pair.key);
				if(PoundData.mslVerified) 
					obj.DISABLED = false;
				else
					obj.DISABLED = true;
				PoundData.poundDataMMGList.push(obj);
			}.bind(this));
			
			this.controller.get('mcdurl').innerHTML = fields.get('mcdurl');
		}
		 else {
			this.controller.showAlertDialog({
		    onChoose: function(value){},
		    message: status,
		    preventCancel:false,
		    choices:[
	        {label: 'Done', value:true, type:'dismiss'}    
		    ]
		  	});	  
			}			
		this.controller.modelChanged(this.browserPrimListModel, this);
		this.controller.modelChanged(this.browserSecListModel, this);
		this.controller.modelChanged(this.mmgListModel, this);
		this.controller.modelChanged(this.mmscurlListModel, this);
	},
	
	primListChangeHandler:function(event) {
				
		if(!event.model)
			return;
		
		var key;
		var value = event.value;
		var params = {};
		
		
		this.primFieldMap.each(function(pair) {
			for(var i=0; i<PoundData.poundDataPrimExtList.length; i++) {
				if(PoundData.poundDataPrimExtList[i].FIELDNAME == pair.value) {
					params[pair.key] = PoundData.poundDataPrimExtList[i].FIELDVALUE;
					break;
				}					
			}			
		}.bind(this));
		
		TelephonyCommands.dataExtFieldsSet(params,null);
	},
	
	secListChangeHandler:function(event) {
				
		if(!event.model)
			return;
		
		var key;
		var value = event.value;
		var params = {};
		
		this.secFieldMap.each(function(pair) {
			for(var i=0; i<PoundData.poundDataSecExtList.length; i++) {
				if(PoundData.poundDataSecExtList[i].FIELDNAME == pair.value) {
					params[pair.key] = PoundData.poundDataSecExtList[i].FIELDVALUE;
					break;
				}					
			}			
		}.bind(this));
		
		TelephonyCommands.dataExtFieldsSet(params,null);
	},
	
	mmgListChangeHandler:function(event) {
				
		if(!event.model)
			return;
		
		var key;
		var value = event.value;
		var params = {};
		//Get the key from the Hash Map
		this.mmgFieldMap.each(function(pair) {
			for(var i=0; i<PoundData.poundDataMMGList.length; i++) {
				if(PoundData.poundDataMMGList[i].FIELDNAME == pair.value) {
					params[pair.key] = PoundData.poundDataMMGList[i].FIELDVALUE;
					break;
				}					
			}			
		}.bind(this));
		
		TelephonyCommands.dataExtFieldsSet(params,null);
	},
	
	mmscurlChangeHandler:function(event) {
		if(!event.model)
			return;
		
		TelephonyCommands.dataExtFieldsSet({mmscurl: event.value},null);
		
		new Mojo.Service.Request(TelephonyCommands.carrierDBUri, { 
			method: 'setOverideRecordSettings', 
			parameters: {"mmsSettings":{"mmscUrl":event.value}},
			onFailure: function(r) {
				QDLogger.error("setOverideRecordSettings failure with response %j",r)
			}
		});
		
		new Mojo.Service.Request(TelephonyCommands.carrierDBUri, {
	        method: 'setOverideRecordUse',
	        parameters: {'useOverride': true},
	        onFailure: function(r) {
				QDLogger.error("setOverideRecordUse failure with response %j",r)
			}
	    });
	},
		
	verifyMSL: function(event,id) {
		this.edited = id;
		if (id !== 'lbs') {
			if (!event.item) 
				return;
			this.selectedRow = event.index;
		}
		
		if(PoundData.mslVerified) {
			this.lbsIpModel.lbsdisabled = false;
			this.lbsPortModel.lbsdisabled = false;
			this.controller.modelChanged(this.lbsIpModel,this);
			this.controller.modelChanged(this.lbsPortModel,this);
			return;
		}
		this.showMSLDialog();
	},
	
	verifiedMSL: function(success,msl) {
		PoundData.mslVerified = success;
		if(success) {
			PoundData.edited = true;
			
			if(this.edited === 'primngg') {
				for(var i=0; i<PoundData.poundDataPrimExtList.length;i++)
					PoundData.poundDataPrimExtList[i].DISABLED = false;	
				this.controller.modelChanged(this.browserPrimListModel, this);
				this.controller.get('primngg').mojo.focusItem(this.browserPrimListModel.items[this.selectedRow]);			
			}
			else if(this.edited === 'secngg'){
				for(var i=0; i<PoundData.poundDataSecExtList.length;i++)
					PoundData.poundDataSecExtList[i].DISABLED = false;	
				this.controller.modelChanged(this.browserSecListModel, this);
				this.controller.get('secngg').mojo.focusItem(this.browserSecListModel.items[this.selectedRow]);			
			}
			else if(this.edited === 'mmg') {
				for(var i=0; i<PoundData.poundDataMMGList.length;i++)
					PoundData.poundDataMMGList[i].DISABLED = false;	
				this.controller.modelChanged(this.mmgListModel, this);
				this.controller.get('mmg').mojo.focusItem(this.browserSecListModel.items[this.selectedRow]);
			}
			else if(this.edited === 'lbs') {
				this.lbsIpModel.lbsdisabled = false;
				this.lbsPortModel.lbsdisabled = false;
				this.controller.modelChanged(this.lbsIpModel,this);
				this.controller.modelChanged(this.lbsPortModel,this);
			}
			else if(this.edited === 'mmscurl') {
				PoundData.poundDataMMSCList[0].DISABLED = false;
				this.controller.modelChanged(this.mmscurlListModel,this);
			}
			
		}		
	},
	
	showMSLDialog: function() {
		this.dialogBox = this.controller.showDialog({
			template: 'template/phone-msl-dialog',
			assistant: new MslAssistant(this),	
			preventCancel: true		
		});
	},
	
	showCarrierAuthDialog: function(onSuccess) {
		this.dialogBox = this.controller.showDialog({
			template: 'template/phone-carrier-auth-dialog',
			assistant: new CarrierAuthDialogAssistant(this, onSuccess),	
			preventCancel: true		
		});
	}	
});
