var g_deviceName = JSON.parse(sessionStorage.getItem("configData"));
var g_connection_settings = [];
var g_calibration_settings = [];


var sleepThread = false
const sleep = ( ms ) => {
    var end = +(new Date()) + ms;
    while( +(new Date()) < end ){ 
		if(sleepThread)
		{
			end = end + 1000;
		}
	} 
}

function ConfigureStatusSettings() {
	var request = new Request();
	request.url = '../devScripts/pilotUIConfig.xml';
	request.parameters = {};
	InvokePythonService(request, "xml").then(function (response) {
		var selectedDevice = $(response).find("Device[code=" + g_deviceName + "]");
		//BindConnectionSettings(selectedDevice);
		BinCalibrationSettings(selectedDevice);
	});
}

ConfigureStatusSettings();



function BinCalibrationSettings(selectedDevice) {
	var setupPage = selectedDevice.find('Page[name="setup"]');
	var calibrationSettings = setupPage.find('tab[name="calibration"]');

	calibrationSettings.find('setting').each(function () {
		var setting = {
			name: $(this).attr('name'),
			subGroupName: $(this).attr('subGroupName'),
			subGroupId: $(this).attr('subGroupId'),
			description: $(this).attr('description'),
			guiName: $(this).attr('gui_name'),
			dbName: $(this).attr('db_name'),
			db_minvalue: $(this).attr('db_minvalue'),
			db_Maxvalue: $(this).attr('db_Maxvalue'),
			db_Tuningvalue: $(this).attr('db_Tuningvalue'),
		}
		g_calibration_settings.push(setting);
	});

	$.each(g_calibration_settings, function (index, item) {
		var settingsHtml = `<div class="row mt-4 pb-4">
								<div class="bottom-level-first-item">
									<span>`+ item.guiName + `</span>
								</div>
								<div class="bottom-level-second-item">
									<div class="form-inline">
										<div class="form-group">
											<label for="minValue">Min Value</label>
											<input type="text" id="minValue" class="form-control common-input-field mx-sm-3" value="`+ item.db_minvalue + `">
										</div>
									</div>
								</div>
								<div class="bottom-level-three-item">
									<div class="form-inline">
										<div class="form-group">
											<label for="setValue">Max Value</label>
											<input type="text" id="setValue" class="form-control common-input-field mx-sm-3" value="`+ item.db_Maxvalue + `">
										</div>
									</div>
								</div>
								<div class="bottom-level-four-item">
									<div class="form-inline">
										<div class="form-group">
											<label for="setValue">Tuning Step</label>
											<input type="text" id="setValue" class="form-control common-input-field mx-sm-3" value="`+ item.db_Tuningvalue + `">
										</div>
									</div>
								</div>
							</div>`;
		$('#' + item.subGroupId).append(settingsHtml);
	});
}



angular.module('setupModule', [])
	.controller('setupController', function ($scope,$filter,$timeout) {
		$scope.moduleControlData = [];
		$scope.demoModeData = [];
		$scope.connectionSettings = [];

		$scope.BindTECData = function(TECLevel){
			var dbData = {};
			if(TECLevel.db_MAP == 'TEC' && !TECLevel.dataLoaded){
				TECLevel.dataLoaded = true;
				var request = new Request();
				request.url = '../cgi/cgi_TECManager.py';
				request.parameters = {"requestType":"read_TEC"};
				InvokePythonService(request).then(function (response) {
					if(response.length < 1){
						alert('no TEC data found');
					}
					else{
						dbData = response[0];
						angular.forEach(TECLevel.data,function (lvlContent,index) {
							angular.forEach(lvlContent.items,function(contentItem,i){
								contentItem.db_value = PopulateDBData(dbData,contentItem.db_name,contentItem.db_value);
							});
						});
					}
					$scope.$apply();
				});					
			}
		};

		$scope.BindModeMapData = function(ModeMap){
			var dbData = {};
			if(ModeMap.db_MAP == 'MODE_MAP' && !ModeMap.dataLoaded){
				ModeMap.dataLoaded = true;
				var request = new Request();
				request.url = '../cgi/cgi_ModeMapManager.py';
				request.parameters = {"requestType":"read_mode_map"};
				InvokePythonService(request).then(function (response) {
					if(response.length < 1){
						alert('no MODE MAP data found');
					}
					else{
						dbData = response[0];
						angular.forEach(ModeMap.data,function (lvlContent,index) {
							angular.forEach(lvlContent.items,function(contentItem,i){
								contentItem.db_value = PopulateDBData(dbData,contentItem.db_name,contentItem.db_value);
							});
						});
					}
					$scope.$apply();
				});					
			}
		};
		
		$scope.BindIDRIVEData = function (levelContent) {			
			if (levelContent.db_MAP == 'IDRIVE' && !levelContent.dataLoaded && levelContent.type == 'CONFIG') {
				levelContent.dataLoaded = true;
				var dbContent = $filter('filter')($scope.IdriveData, { IDriveId: levelContent.dbId });
				
				angular.forEach(levelContent.items, function (item, index) {
					item.db_value = PopulateDBData(dbContent[0], item.db_name, item.db_value);
				});
			}
			else if(levelContent.db_MAP == 'IDRIVE' && !levelContent.dataLoaded && levelContent.type == 'READONLY')
			{
				levelContent.dataLoaded = true;
				var dbContent = $filter('filter')($scope.IdriveData, { IDriveId: levelContent.dbId });
				levelContent.db_value = PopulateDBData(dbContent[0], levelContent.db_name, levelContent.db_value);
			}
		}
		$scope.BindRFAMPData = function (levelContent) {			
			if (levelContent.db_MAP == 'RF_AMP' && !levelContent.dataLoaded && levelContent.type == 'CONFIG') {
				levelContent.dataLoaded = true;
				var dbContent = $filter('filter')($scope.RFAmpData, { section_id: 4 });
				
				angular.forEach(levelContent.items, function (item, index) {
					item.db_value = PopulateDBData(dbContent[0], item.db_name, item.db_value);
				});
			}
			else if(levelContent.db_MAP == 'RF_AMP' && !levelContent.dataLoaded && levelContent.type == 'READONLY')
			{
				levelContent.dataLoaded = true;
				var dbContent = $filter('filter')($scope.RFAmpData, { section_id: 4 });
				levelContent.db_value = PopulateDBData(dbContent[0], levelContent.db_name, levelContent.db_value);
			}
		}

		$scope.GetHierarchyData = function(settings,tabName)
		{

			settings.children('level[levelOrder="1"]').each(function () {
				var levelContent = [];
				var mapContent = [];
				var levelxml = $(this);

				
				
				

				// if(sleepThread){
				// 	sleep(4000);
				// }
					
				

				levelxml.children('levelContent').each(function () {
					var items = [];
					var levelContentxml = $(this);
					levelContentxml.children('item').each(function () {
						items.push({type:$(this).attr('type'),gui_name:$(this).attr('gui_name'), db_value: $(this).attr('db_value'), db_name: $(this).attr('db_name'),gui_class:$(this).attr('gui_class')});
					});
					levelContent.push({items:items,type:levelContentxml.attr('type'),gui_name:levelContentxml.attr('gui_name'),gui_class:levelContentxml.attr('gui_class')})
				});

				levelxml.children('maps').each(function () {
					var maps = [];
					var mapsContentxml = $(this);
					mapsContentxml.children('map').each(function () {
						maps.push({gui_name:$(this).attr('gui_name'),id:$(this).attr('id')});
					});
					mapContent.push({maps:maps,gui_name:mapsContentxml.attr('gui_name'),id:mapsContentxml.attr('id')})
				});

				if(tabName == "moduleControl")
				{
					$scope.moduleControlData.push(
						{
							name:levelxml.attr('name'),
							db_MAP:levelxml.attr('db_MAP'),
							data: levelContent,
							childLevels : $scope.GetXmlConfig(levelxml,2),
							mapConfig:mapContent
						});	
				console.log($scope.moduleControlData);	

				}	
				else
				{
					$scope.demoModeData.push(
						{
							name:levelxml.attr('name'),
							data: levelContent,
							childLevels : $scope.GetXmlConfig(levelxml,2),
							mapConfig:$scope.GetMapsInfo(settings)
						});
				console.log($scope.demoModeData);	

				}

			});
		}

		function PopulateDBData(dbObject,key,defaultVal)
		{
			if(dbObject !=undefined && dbObject !=null && key !="")
				return dbObject[key];
			else
				return defaultVal;
		}

		$scope.GetMapsInfo = function(mapsConfig)
		{
			var mapsData = [];

			mapsConfig.children('Maps').find('map').each(function () {
				var map = {
					divId:$(this).attr('mapId'),
					mapFunction:$(this).attr('mapFunction')
				};
				mapsData.push(map);
			});
			return mapsData;
		};

		$scope.GetXmlConfig = function(settings,levelOrder)
		{
			var moduleControlData = [];
			settings.children('level[levelOrder="'+levelOrder+'"]').each(function () {
				var levelContent = [];
				var mapContent = [];
				var levelxml = $(this);
				
				levelxml.children('levelContent').each(function () {
					var items = [];
					var levelContentxml = $(this);
					levelContentxml.children('item').each(function () {
						items.push({type:$(this).attr('type'),gui_name:$(this).attr('gui_name'),db_name:$(this).attr('db_name'),db_value:$(this).attr('db_value'),gui_class:$(this).attr('gui_class')});
					});
					levelContent.push({items:items,type:levelContentxml.attr('type'),gui_name:levelContentxml.attr('gui_name'),db_MAP:levelContentxml.attr('db_MAP'),dbId:levelContentxml.attr('dbId'),db_name:$(this).attr('db_name'),db_value:$(this).attr('db_value')})
				});

				levelxml.children('maps').each(function () {
					var maps = [];
					var mapsContentxml = $(this);
					mapsContentxml.children('map').each(function () {
						maps.push({gui_name:$(this).attr('gui_name'),id:$(this).attr('id')});
					});
					mapContent.push({maps:maps,gui_name:mapsContentxml.attr('gui_name'),id:mapsContentxml.attr('id')})
				});

				moduleControlData.push(
					{
						name:levelxml.attr('name'),
						data: levelContent,
						childLevels : $scope.GetXmlConfig(levelxml,levelOrder+1),
						mapConfig:mapContent,
						levelOrder : levelOrder
					});								
			});

			return moduleControlData;
		}

		var request = new Request();
		request.url = '../cgi/cgi_Setup_ModuleControl.py';
		request.parameters = { };
		InvokePythonService(request).then(function (response) {
			$scope.IdriveData = response;
		});

		var request = new Request();
		request.url = '../cgi/cgi_RFAmp.py';
		request.parameters = {"requestType":"read_RFAmp" };
		InvokePythonService(request).then(function (response) {
			$scope.RFAmpData = response;
		});

		$scope.GetConnectionTabSettings = function(selectedDevice){
				$scope.connectionSettings.ethernet = [];
				$scope.connectionSettings.serial = [];
				var setupPage = selectedDevice.find('Page[name="setup"]');
				var connectionSettings = setupPage.find('tab[name="connection"]');
			
				var request = new Request();
				request.url = '../cgi/cgi_IpCfgManager.py';
				request.parameters = {"requestType":"read_IP"};
				InvokePythonService(request).then(function (response) {
					if(response.length > 0)
						var settings = response[0];	
					else
						var settings = {"id":"","name":"","state":"","ip_addr":"","netmask":"","gateway":"","dns":"","enabled":0};		
					
					$scope.connectionSettings.isEthernerEnabled = settings["enabled"] == 1 ? true:false;

					connectionSettings.find('setting[subGroupName="Ethernet"]').each(function () {
						var setting = {
							name: $(this).attr('name'),
							subGroupName: $(this).attr('subGroupName'),
							subGroupId: $(this).attr('subGroupId'),
							description: $(this).attr('description'),
							guiName: $(this).attr('gui_name'),
							dbName: $(this).attr('db_name'),
							dbValue: settings[$(this).attr('db_name')] //$(this).attr('db_value'),
						}
						$scope.connectionSettings.ethernet.push(setting);
					});	
				});

				var request = new Request();
				request.url = '../cgi/cgi_SerialManager.py';
				request.parameters = {"requestType":"read_serial"};
				InvokePythonService(request).then(function (response) {
					if(response.length > 0)
						var settings = response[0];	
					else
						var settings = {"name":"","state":"","baud_rate":"","parity":"","data_bits":"","flow_control":"","flow_control":"","enabled":0};		

					$scope.connectionSettings.isSerialEnabled = settings["enabled"] == 1 ? true:false;					

					connectionSettings.find('setting[subGroupName="Serial"]').each(function () {
						var setting = {
							name: $(this).attr('name'),
							subGroupName: $(this).attr('subGroupName'),
							subGroupId: $(this).attr('subGroupId'),
							description: $(this).attr('description'),
							guiName: $(this).attr('gui_name'),
							dbName: $(this).attr('db_name'),
							dbValue: settings[$(this).attr('db_name')] //$(this).attr('db_value'),
						}
						$scope.connectionSettings.serial.push(setting);
					});	
				});

				var request = new Request();
				request.url = '../cgi/cgi_RemoteControl.py';
				request.parameters = {"requestType":"read_remote_control"};
				InvokePythonService(request).then(function (response) {
					if(response.length > 0)
						var settings = response[0];	
					else
						var settings = {"enabled":0};		

					$scope.connectionSettings.isRemoteControlEnabled = settings["enabled"] == 1 ? true:false;	
				});
		}

		$scope.Init = function(){
			var request = new Request();
			request.url = '../devScripts/pilotUIConfig.xml';
			request.parameters = {};
			InvokePythonService(request, "xml").then(function (response) {
				var selectedDevice = $(response).find("Device[code=" + g_deviceName + "]");
				var setupPage = selectedDevice.find('Page[name="setup"]');
				
				var moduleSettings = setupPage.find('tab[name="moduleControl"]');
				
				var demoSettings = setupPage.find('tab[name="demoMode"]');

				$scope.GetHierarchyData(moduleSettings,"moduleControl");
				$scope.GetHierarchyData(demoSettings,"demoMode");
				$scope.GetConnectionTabSettings(selectedDevice);

				$timeout(function () {
					$scope.$digest();
					//nestedAccordionFunctionality();
					RenderIntensityChart('divIntensity0');
					RenderIntensityChart('divIntensity1');
					opticalFrequencyComb();
					ReflectorA();
					ReflectorB();
					ReflectorAA();
					ReflectorBB();
				}, 2000);
			});
		};
		$scope.Init();
		$scope.SaveConnectionSettings = function(connectionType){
			
			if(connectionType == 2){
				var serial = $scope.connectionSettings.serial;

				var request = new Request();
				request.url = '../cgi/cgi_SerialManager.py';
				request.parameters = {"requestType":"create_serial","baud_rate":GetDBValue(serial,"baud_rate"),"parity":GetDBValue(serial,"parity"),"data_bits":GetDBValue(serial,"data_bits"),"flow_control":GetDBValue(serial,"flow_control"),"enabled":$scope.connectionSettings.isSerialEnabled?1:0};
				InvokePythonService(request).then(function (response) {
					alert('Serial: ' + response.description);
				});
			}

			if(connectionType == 1){
				var ipconfig = $scope.connectionSettings.ethernet;
				var request = new Request();
				request.url = '../cgi/cgi_IpCfgManager.py';
				request.parameters = {"requestType":"create_IP","ip_addr":GetDBValue(ipconfig,"ip_addr"),"netmask":GetDBValue(ipconfig,"netmask"),"gateway":GetDBValue(ipconfig,"gateway"),"dns":GetDBValue(ipconfig,"dns"),"enabled":$scope.connectionSettings.isEthernerEnabled?1:0};
				InvokePythonService(request).then(function (response) {
					alert('Ethernet: ' + response.description);
				});
			}

			if(connectionType == 3){
				var request = new Request();
				request.url = '../cgi/cgi_RemoteControl.py';
				request.parameters = {"requestType":"create_remote_control","enabled":$scope.connectionSettings.isRemoteControlEnabled?1:0};
				InvokePythonService(request).then(function (response) {
					alert('Remote control: ' + response.description);
				});
			}
		};		
	
		//Email config

		$scope.GetEmailConfig = function()
		{
			var request = new Request();
			request.url = '../cgi/cgi_EmailManager.py';
			request.parameters = {"requestType":"read_email"};
			InvokePythonService(request).then(function (response) {
				$scope.AlertMessages = [{"name":"Info","id":1,"isSelected":false},{"name":"Warning","id":2,"isSelected":false},{"name":"Alert","id":3,"isSelected":false}];

				if(response.length > 0)
				{
					$scope.emailConfig = response[0];
					$scope.emailConfig.alert_msg = $scope.emailConfig.alert_msg == "true";
					$scope.emailConfig.authentication = $scope.emailConfig.authentication == "true";

					if($scope.emailConfig.level.length>0){
						angular.forEach($scope.AlertMessages, function (item, key) { 
							if($scope.emailConfig.level.indexOf(item.id) > -1)
							$scope.AlertMessages[key].isSelected = true;
						}); 
					}
				}
				else{
					$scope.emailConfig =	{"name":"","state":"","level":"","user":"","pw":"","out_server":"","in_server":"","authentication":false,"smtp_server":"sdfs","port_number":"","alert_msg":false,"id":""}
				}
				$scope.$apply();
			});
		}
		$scope.SaveEmailConfig = function()
		{
			var reqParams = $scope.emailConfig;
			var alerts = $filter('filter')($scope.AlertMessages, { isSelected: true });
			reqParams.level = Array.prototype.map.call(alerts , s => s.id).toString();
			reqParams.requestType = "create_email";

			var request = new Request();
			request.parameters = reqParams;
			request.url = '../cgi/cgi_EmailManager.py';
			InvokePythonService(request).then(function (response) {
				alert(response.description);
			});
		}

		$scope.RenderRangeSlider_new_change = function(levelContent)
		{
			// $('#hdn_minWavelength').val(levelContent.SliderSetValue);			
			// $('#hdn_minWavelength').rangeControl({delim: ' '});
		}
		$scope.RenderRangeSlider_new = function(levelContent,sliderName)
		{
			$timeout(function () {
				if(sliderName == 'minWavelength')
				{
					levelContent.minVal = GetPropertyValue(levelContent.items,'minWavelength','db_name');
					levelContent.maxVal = GetPropertyValue(levelContent.items,'maxWaveLength','db_name');
					levelContent.SliderSetValue = GetPropertyValue(levelContent.items,'setWaveLength','db_name');
					levelContent.interval = GetPropertyValue(levelContent.items,'wavelengthInterval','db_name');

					levelContent.interval = Math.floor((levelContent.maxVal-levelContent.minVal)/levelContent.interval);
					$scope.$apply();
				}

				var tempVal = levelContent.minVal;
				var calculatedInterval = levelContent.interval;//Math.floor((levelContent.maxVal-levelContent.minVal)/levelContent.interval);
				var labelsArray = [];
				labelsArray.push(tempVal);
				while ((tempVal + calculatedInterval) < levelContent.maxVal) {
					tempVal = tempVal + calculatedInterval;
					labelsArray.push(tempVal);
				}

				var config = {
					min:levelContent.minVal,
					max:tempVal,
					step:calculatedInterval,
					currentValue: false,
					scale:{
						labels:labelsArray,
						interval:calculatedInterval
					}
				}
				var sliderConfig = '{"min":0,"max": 40,"step":10, "currentValue": false, "scale": {"labels": [0,10,20,30,40], "interval": 10}}'
				$('#hdn_minWavelength').attr('data-options',angular.toJson(config));
				$timeout(function () {
					// $('#hdn_minWavelength').rangeControl({delim: ' '});
					// $('#hdn_minWavelength').on('rangeControlChange.rangeControlEvent', function () {					
					// 	levelContent.SliderSetValue = parseInt($(this).val()) ;
					// 	$scope.$apply();
					// });
					// $('#hdn_minWavelength').on('rangeControlSlide.rangeControlEvent', function () {
					// 	console.log($(this).val());
					// }); 
				},6000); 
			},3000);
		};
		
		$scope.RenderRangeSlider = function(levelContent,sliderName)
		{
			$timeout(function () {
				if(sliderName == 'minWavelength')
				{
					levelContent.minVal = GetPropertyValue(levelContent.items,'minWavelength','db_name');
					levelContent.maxVal = GetPropertyValue(levelContent.items,'maxWaveLength','db_name');
					levelContent.SliderSetValue = GetPropertyValue(levelContent.items,'setWaveLength','db_name');
					levelContent.interval = GetPropertyValue(levelContent.items,'wavelengthInterval','db_name');

					$scope.$apply();
				}
			},3000);
		};

		$scope.range = function(min, max, step) {
			step = step || 1;
			var input = [];
			for (var i = min; i <= max; i += step) {
				input.push(i);
			}
			return input;
		};

		$scope.RenderSlider = function(levelContent,SliderName){
			$timeout(function () {
				var setValue = 0;
				var setInputId = '';

				if(SliderName == 'setMinTemp'){
					var maxVal = GetPropertyValue(levelContent.items,'setMaxTemp','db_name');
					var minVal = GetPropertyValue(levelContent.items,'setMinTemp','db_name');
					setValue = GetPropertyValue(levelContent.items,'setTemp','db_name');
					setInputId = 'setTemp'
					//$scope.SliderSetValue = GetPropertyValue(levelContent.items,'setTemp','db_name');
				}
				else if(SliderName == 'minSMSR')
				{
					var maxVal = GetPropertyValue(levelContent.items,'maxSMSR','db_name');
					var minVal = GetPropertyValue(levelContent.items,'minSMSR','db_name');
					//$scope.SliderSetValue = GetPropertyValue(levelContent.items,'setSMSR','db_name');
					setValue = GetPropertyValue(levelContent.items,'setSMSR','db_name');
					setInputId = 'setSMSR'
				}
				else if(SliderName == 'setMinDR')
				{
					var maxVal = GetPropertyValue(levelContent.items,'setMaxDR','db_name');
					var minVal = GetPropertyValue(levelContent.items,'setMinDR','db_name');
					//$scope.SliderSetValue = GetPropertyValue(levelContent.items,'setSMSR','db_name');
					setValue = GetPropertyValue(levelContent.items,'setDR','db_name');
					setInputId = 'setSMSR'
				}
				else{
					var maxVal = GetPropertyValue(levelContent.items,levelContent.items[2].db_name,'db_name');
					var minVal = GetPropertyValue(levelContent.items,levelContent.items[1].db_name,'db_name');
					setValue = GetPropertyValue(levelContent.items,levelContent.items[3].db_name,'db_name');
					SliderName = SliderName+""+levelContent.dbId
				}
				levelContent.SliderSetValue =setValue;

				//$('#hdn_sliderSet_'+SliderName).val(setValue);
				//$('#INPUT_SLIDER_'+setInputId).val(setValue);


				// levelContent.Slider = {};
				// levelContent.Slider = {maxVal:maxVal,};
				//Added, set initial value.

				$("#slider_"+SliderName).slider({
					animate: true,
					value:levelContent.SliderSetValue,
					min: minVal,
					max: maxVal,
					step: 1,
					slide: function(event, ui) {
						//$scope.UpdateSlider(SliderName,ui.value);
						//$scope.SliderSetValue = ui.value;

						//$('#hdn_sliderSet_'+SliderName).val(ui.value).trigger('change');
						//$('#INPUT_SLIDER_'+SliderName).val(ui.value);

						// var element = $('#hdn_sliderSet_'+SliderName);
						// element.val(ui.value);
						// element.trigger('input');
						levelContent.SliderSetValue =ui.value;


						$('#slider_'+ SliderName +' a').html('<label><span class="glyphicon glyphicon-chevron-left"></span>'+ui.value+' <span class="glyphicon glyphicon-chevron-right"></span></label>');
						$scope.$apply();
					}
				});	

				//$scope.UpdateSlider(SliderName,$scope.SliderSetValue);
				

				$('#slider_'+ SliderName +' a').html('<label><span class="glyphicon glyphicon-chevron-left"></span>'+setValue+' <span class="glyphicon glyphicon-chevron-right"></span></label>');
				$scope.$apply();	
			},3000);	
		};

		$scope.UpdateSlider =function(slider,val) {
			//changed. Now, directly take value from ui.value. if not set (initial, will use current value.)
			var $amount = slider == 'setMinTemp'? val:$scope.SliderSetValue;	
	
			$scope.SliderSetValue = $amount;
			//'#slider a'
			$('#slider_'+ slider +' a').html('<label><span class="glyphicon glyphicon-chevron-left"></span>'+$amount+' <span class="glyphicon glyphicon-chevron-right"></span></label>');

			$scope.$apply();
		}
		$scope.SaveModuleControl =function()
		{
			console.log($scope.moduleControlData);
			var tecData = $scope.moduleControlData[0].data[1].items;
			var request = new Request();
			request.url = '../cgi/cgi_TECManager.py';
			request.parameters = {"requestType":"update_TEC","setTemp":$scope.moduleControlData[0].data[1].SliderSetValue,"onOffState":GetPropertyValue(tecData,"onOffState","db_name")?1:0};
			InvokePythonService(request).then(function (response) {
				alert('TEC: ' + response.description);
			});

			//mode-map
			var modeMapData_wavelength = $scope.moduleControlData[1].data[0];
			var modeMapData_DR = $scope.moduleControlData[1].data[1];
			var modeMapData_smsr = $scope.moduleControlData[1].data[2];

			//temp fix:
			modeMapData_wavelength.SliderSetValue = $('#INPUT_SLIDER_setWaveLength').val()

			var request = new Request();
			request.url = '../cgi/cgi_ModeMapManager.py';
			request.parameters = {"requestType":"update_mode_map","set_wavelength":modeMapData_wavelength.SliderSetValue,"get_smsr":modeMapData_smsr.SliderSetValue,"state":GetPropertyValue(modeMapData_DR.items,"state","db_name")?1:0};
			InvokePythonService(request).then(function (response) {
				alert('Mode Map: ' + response.description);
			});

			//Idrive Save
			
			$scope.SaveIDriveData($scope.moduleControlData[1].childLevels);

			$scope.SaveRFAmp($scope.moduleControlData[1].childLevels[1].childLevels[1].data[2], $scope.moduleControlData[1].childLevels[1].childLevels[1].data[3]);
			
			alert('Idrive data updated successfully');
		}

		$scope.SaveRFAmp = function(frequencyData , powerData){
			var request = new Request();
			request.url = '../cgi/cgi_RFAmp.py';
			request.parameters = {"requestType":"update_RFAmp","set_Frequency":frequencyData.SliderSetValue,"set_Power":powerData.SliderSetValue,"OnOffState":GetPropertyValue(powerData.items,"OnOffState","db_name")?1:0};
			InvokePythonService(request).then(function (response) {
				alert('RF Amp: ' + response.description);
			});
		}
	

		$scope.SaveIDriveData = function(childLevels)
		{
			angular.forEach(childLevels,function (child,index) {
				if(child.data.length > 0 && child.data[0].db_MAP == 'IDRIVE')
				{
					var configItems = child.data[0].items;
					var iDriveId = child.data[0].dbId;

					var request = new Request();
					request.url = '../cgi/cgi_Setup_ModuleControl.py';
					request.parameters = {"requestType":"update_Section","id":iDriveId,"minValue":GetPropertyValue(configItems,"MinValue","db_name"),"maxValue":GetPropertyValue(configItems,"MaxValue","db_name"),"setValue":child.data[0].SliderSetValue,"onOffState":GetPropertyValue(configItems,"OnOffState","db_name")?1:0};
					InvokePythonService(request).then(function (response) {
						console.log('IDrive: ' + response.description);
					});
				}
				if(child.childLevels.length >0)
				{
					$scope.SaveIDriveData(child.childLevels);
				}
			});		
		};

		$scope.switchTitles =["Turn Data OFF","Turn Data ON"];
		$scope.getSwitchTitle = function(isTrue){
			return isTrue ? $scope.switchTitles[0]:$scope.switchTitles[1]
		}
	});
//Private functions

function GetDBValue(objectSettings,property)
{
	var result = jQuery.grep(objectSettings, function( item, i ) {
		return ( item.dbName == property);
	});
	return result[0].dbValue
};

function GetPropertyValue(objectSettings,property,key)
{
	var result = jQuery.grep(objectSettings, function( item, i ) {
		return ( item[key] == property);
	});
	return result[0]['db_value'];
};
function ConfigureDiscreteSlider()
{
	setTimeout(function(){
		$('#hdn_minWavelength').rangeControl({delim: ' '});
		$('#hdn_minWavelength').on('rangeControlChange.rangeControlEvent', function () {					
			// $('#INPUT_SLIDER_setWaveLength').val(parseInt($(this).val()));
			// $('#INPUT_SLIDER_setWaveLength').trigger('input');

			var element = $('#INPUT_SLIDER_setWaveLength');
			element.val(parseInt($(this).val()));
			element.trigger('input');
			
		});
		$('#hdn_minWavelength').on('rangeControlSlide.rangeControlEvent', function () {
			console.log($(this).val());
		}); 
	}, 3000);
}