var calibrationData;
let calibrationParameters = [
	{
		moduleType: "calibrationData",
		url: "../cgi/cgi_Calibration.py",
		data: {
			requestType: "read_calibration",
		}
	},
]
function loadCalibrationData() {
	calibrationParameters.forEach(function (parameter) {
		$.ajax({
			type: "Get",
			url: parameter.url,
			async: false,
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			data: parameter.data,
			success: function (response) {
				calibrationData = response[0]
				switch (parameter.moduleType) {
					case "calibrationData":
						if(response.length > 0){
							$("#ring_start_voltage_1").val(response[0]?.ring_start_voltage_1 ?? 0);
							$("#ring_stop_voltage_1").val(response[0].ring_stop_voltage_1);
							$("#ring_increment_1").val(response[0].ring_increment_1);
							$("#r1_current").val(response[0].r1_cur ? response[0].r1_cur : 0);
							$("#ring_start_voltage_2").val(response[0].ring_start_voltage_2 ?? 0);
							$("#ring_stop_voltage_2").val(response[0].ring_stop_voltage_2);
							$("#ring_increment_2").val(response[0].ring_increment_2);
							$("#r2_current").val(response[0].r2_cur ? response[0].r2_cur : 0);
							$("#phase_start_voltage").val(response[0].phase_start_voltage ?? 0);
							$("#phase_stop_voltage").val(response[0].phase_stop_voltage);
							$("#phase_increment").val(response[0].phase_increment);
							$("#phase_current").val(response[0].phase_cur ? response[0].phase_cur : 0);
							$("#gain_start_current").val(response[0].gain_start_current ?? 0);
							$("#gain_stop_current").val(response[0].gain_stop_current);
							$("#gain_increment").val(response[0].gain_inc);
							$("#gain_current").val(response[0].gain_cur ? response[0].gain_cur : 0);
							$("#start_temperature").val(response[0].start_temperature);
							$("#stop_temperature").val(response[0].stop_temperature);
							$("#temp_increment").val(response[0].temp_inc);
							$("#temp_current").val(response[0].temp_cur ? response[0].temp_cur : 0);
							$("#detector").val(response[0].detector ?? 0);
							// $("#location").val(response[0].location);
							$("#soa_start").val(response[0].soa_start ?? 0);
							$("#soa_stop").val(response[0].soa_stop);
							$("#soa_inc").val(response[0].soa_inc);
							$("#soa_current").val(response[0].soa_current ? response[0].soa_current : 0);
						}
						break;
				}
			},
			error: function (ex) {
				$("#test").html(ex.responseText)
			}
		});
	});
}

$(document).ready(function(){
	// $("#stop-calibration").attr("disabled","disabled")
	const platform = navigator.platform;

	if (platform.startsWith('Win')) {
		$("#location").val("C:\\Downloads\\filename.csv");
	// Windows
	// console.log('This site is being viewed on Windows');
	} else if (platform.startsWith('Mac')) {
		$("#location").val("home\\Downloads\\filename.csv");
	// macOS
	// console.log('This site is being viewed on macOS');
	} else if (platform.startsWith('Linux')) {
		$("#location").val("home\\Downloads\\filename.csv");
	// Linux
	// console.log('This site is being viewed on Linux');
	} else {
	// Other platform
	// console.log('This site is being viewed on an unknown platform');
	}
	

	loadCalibrationData();

	// if ($("#cal-wavelength-slider").next().length == 0) {
	// 	loadSlider(calibrationWaveSliderObj, "#cal-wavelength-slider", "#cal-wavelength-setvalue", 0, 100, 25, caliSliders, true, 1, true, 0, false);
	// 	loadSlider(calibrationFreqSliderObj, "#cal-frequency-slider", "#cal-frequency-setvalue", 0, 100, 25, caliSliders, true, 1, true, 0, false);
	// 	$("#cal-wavelength-setvalue").prop("disabled", true);
	// 	$("#cal-frequency-setvalue").prop("disabled", true);
	// }

    $('#start-btn').click(function () {
		$.ajax({
			type: "Get",
			url: "../cgi/cgi_Calibration.py",
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			data: {
				requestType: "start_calibration"
			},
			success: function (response) {
				showModal(response.status, response.description);
			},
			error: function (ex) {
				$("#test").html(ex.responseText);
				
			}
		
		});
	});

    $("#cal-wavelength-setvalue").change(function () {
		var value = parseFloat(parseFloat($(this).val()).toFixed(2));
		calibrationWaveSliderObj.slider.setValues(value, 100)
	});

	$("#cal-frequency-setvalue").change(function () {
		var value = parseFloat(parseFloat($(this).val()).toFixed(2));
		calibrationFreqSliderObj.slider.setValues(value, 100)
	});


	$("#operationDropdown").change(function () {
		if ($(this).val() == "OPS") {
			$("#demultiplexer1Value").text('Scope detected');
		} else {
			$("#demultiplexer1Value").text('OSA detected');
		}

		if (parseInt($(this).val()) == -1) {
			$("#cal-wavelength-setvalue").prop("disabled", true);
			$("#cal-frequency-setvalue").prop("disabled", true);
			calibrationWaveSliderObj.slider.conf.isIDrive = true;
			calibrationFreqSliderObj.slider.conf.isIDrive = true;
			
		} else {
			$("#cal-wavelength-setvalue").prop("disabled", false);
			$("#cal-frequency-setvalue").prop("disabled", false);
			calibrationWaveSliderObj.slider.conf.isIDrive = false;
			calibrationFreqSliderObj.slider.conf.isIDrive = false;
		}
	});

    $("#cal-wavelength-setvalue-debug").change(function () {
		var value = parseFloat(parseFloat($(this).val()).toFixed(2));
		calibrationWaveSliderObj.slider.setValues(value, 100)
	});
	var timeInterval;
	$("#save_calibration").click((e)=> {
		// $("#stop-calibration").attr("disabled",false)
		$("#save_calibration").attr("disabled","disabled").html(`In Progress...`)
		// timeInterval = setTimeout(()=> {
			saveCalibrationData();
		// },15000)
	})
	$("#stop-calibration").click(()=> {
		// if(timeInterval){
			$("#stop-calibration").attr("disabled","disabled")
			// clearInterval(timeInterval);
			$("#save_calibration").html(`Start`);
			timeInterval = ""
			$.ajax({
				type: "Get",
				url: "../cgi/cgi_Calibration.py",
				contentType: 'application/json',
				dataType: 'json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				data: {
					requestType: "stop_calibration"
				},
				success: function (response) {
					$("#stop-calibration").attr("disabled",false)
					showModal("Alert","Calibration Stopped!");
					// showModal(response.status, response.description);
				},
				error: function (ex) {
					$("#test").html(ex.responseText);
					
				}
			
			});
		// }
	})
	function saveCalibrationData() {
		let ring_start_voltage_1 =  $("#ring_start_voltage_1").val();
		let ring_stop_voltage_1 =  $("#ring_stop_voltage_1").val();
		let ring_increment_1 =  $("#ring_increment_1").val();
		let r1_current =  $("#r1_current").val();
		let ring_start_voltage_2 =  $("#ring_start_voltage_2").val();
		let ring_stop_voltage_2 =  $("#ring_stop_voltage_2").val();
		let ring_increment_2 =  $("#ring_increment_2").val();
		let r2_current =  $("#r2_current").val();
		let phase_start_voltage =  $("#phase_start_voltage").val();
		let phase_stop_voltage =  $("#phase_stop_voltage").val();
		let phase_increment =  $("#phase_increment").val();
		let phase_current =  $("#phase_current").val();
		let gain_start_current =  $("#gain_start_current").val();
		let gain_stop_current =  $("#gain_stop_current").val();
		let gain_increment =  $("#gain_increment").val();
		let gain_current =  $("#gain_current").val();
		let start_temperature =  $("#start_temperature").val();
		let stop_temperature =  $("#stop_temperature").val();
		let temp_increment =  $("#temp_increment").val();
		let temp_current =  $("#temp_current").val();
		let detector =  $("#detector").val();
		let location =  $("#location").val();
		let soa_start =  $("#soa_start").val();
		let soa_stop =  $("#soa_stop").val();
		let soa_inc =  $("#soa_inc").val();
		let soa_current =  $("#soa_current").val();
		try {
			
			$.ajax({
				type: "Get",
				url: "../cgi/cgi_Calibration.py",
				contentType: 'application/json',
				dataType: 'json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				data: {
					requestType: "create_calibration",
					ring_start_voltage_1 : ring_start_voltage_1, 
					ring_stop_voltage_1 : ring_stop_voltage_1,
					ring_increment_1 : ring_increment_1,
					r1_current : r1_current,
					ring_start_voltage_2 : ring_start_voltage_2,
					ring_stop_voltage_2 : ring_stop_voltage_2,
					ring_increment_2 : ring_increment_2,
					r2_current : r2_current,
					phase_start_voltage : phase_start_voltage,
					phase_stop_voltage : phase_stop_voltage, 
					phase_increment : phase_increment,
					phase_current : phase_current,
					gain_start_current : gain_start_current,
					gain_stop_current : gain_stop_current,
					gain_increment : gain_increment,
					gain_current : gain_current,
					start_temperature : start_temperature,
					stop_temperature : stop_temperature,
					temp_increment : temp_increment,
					temp_current : temp_current,
					detector : detector,
					location : location,
					soa_start : soa_start,
					soa_stop : soa_stop,
					soa_inc : soa_inc,
					soa_current : soa_current
				},
				success: function (response) {
					timeInterval = ""
					$("#save_calibration").attr("disabled",false).html(`Start`);
					if(response.status == "fail"){

						showModal("Error", response.description);
					}
					else{
						showModal(response.status, response.description);
					}
				},
				error: function (ex) {
					console.log(ex);
					// $("#test").html(ex.responseText);
					
				}
			
			});
		} catch (error) {
			console.log(error);
		}

	}
})

$("#calibration-cancel-btn").click(()=> {
	const platform = navigator.platform;
	let i = 0;
	if($("#ring_start_voltage_1").val() != calibrationData.ring_start_voltage_1 && $("#ring_start_voltage_1").val()){
		i++
	}
	if($("#ring_stop_voltage_1").val() != calibrationData.ring_stop_voltage_1 && $("#ring_stop_voltage_1").val()){
		i++
	}
	if($("#ring_increment_1").val() != calibrationData.ring_increment_1 && $("#ring_increment_1").val()){
		i++;
	}
	// if($("#r1_current").val() != calibrationData.r1_cur && $("#r1_current").val()){
	// 	i++;
	// }
	if($("#ring_start_voltage_2").val() != calibrationData.ring_start_voltage_2 && $("#ring_start_voltage_2").val()){
		i++;
	}
	if($("#ring_stop_voltage_2").val() != calibrationData.ring_stop_voltage_2 && $("#ring_stop_voltage_2").val()){
		i++;
	}
	if($("#ring_increment_2").val() != calibrationData.ring_increment_2 && $("#ring_increment_2").val()){
		i++;
	}
	// if($("#r2_current").val() != calibrationData.r2_cur && $("#r2_current").val()){
	// 	i++;
	// }
	if($("#phase_start_voltage").val() != calibrationData.phase_start_voltage && $("#phase_start_voltage").val()){
		i++;
	}
	if($("#phase_stop_voltage").val() != calibrationData.phase_stop_voltage && $("#phase_stop_voltage").val()){
		i++;
	}
	if($("#phase_increment").val() != calibrationData.phase_increment && $("#phase_increment").val()){
		i++;
	}
	// if($("#phase_current").val() != calibrationData.phase_cur && $("#phase_current").val()){
	// 	i++;
	// }
	if($("#gain_start_current").val() != calibrationData.gain_start_current && $("#gain_start_current").val()){
		i++;
	}
	if($("#gain_stop_current").val() != calibrationData.gain_stop_current && $("#gain_stop_current").val()){
		i++;
	}
	if($("#gain_increment").val() != calibrationData.gain_inc && $("#gain_increment").val()){
		i++;
	}
	// if($("#gain_current").val() != calibrationData.gain_cur && $("#gain_current").val()){
	// 	i++;
	// }
	if($("#start_temperature").val() != calibrationData.start_temperature && $("#start_temperature").val()){
		i++;
	}
	if($("#stop_temperature").val() != calibrationData.stop_temperature && $("#stop_temperature").val()){
		i++;
	}
	if($("#temp_increment").val() != calibrationData.temp_inc && $("#temp_increment").val()){
		i++;
	}
	// if($("#temp_current").val() != calibrationData.temp_cur && $("#temp_current").val()){
	// 	i++;
	// }
	if($("#detector").val() != calibrationData.detector && $("#detector").val()){
		i++;
	}
	if($("#soa_start").val() != calibrationData.soa_start && $("#soa_start").val()){
		i++;
	}
	if($("#soa_stop").val() != calibrationData.soa_stop && $("#soa_stop").val()){
		i++;
	}
	if($("#soa_inc").val() != calibrationData.soa_inc && $("#soa_inc").val()){
		i++;
	}
	// if($("#soa_current").val() != calibrationData.soa_current && $("#soa_current").val()){
	// 	i++;
	// }
	if (platform.startsWith('Win')) {
		if($("#location").val() != "C:\\Downloads\\filename.csv"){
			i++;
		}
	// Windows
	// console.log('This site is being viewed on Windows');
	} else if (platform.startsWith('Mac')) {
		if($("#location").val() != "home\\Downloads\\filename.csv"){
			i++;
		}
	// macOS
	// console.log('This site is being viewed on macOS');
	} else if (platform.startsWith('Linux')) {
		if($("#location").val() != "home\\Downloads\\filename.csv"){
			i++;
		}
	// Linux
	// console.log('This site is being viewed on Linux');
	}
	if(i> 0)
		showModal('Alert', "Changes reversed");
	else 
		showModal('Alert', "No changes detected");


	$("#ring_start_voltage_1").val(calibrationData.ring_start_voltage_1);
	$("#ring_stop_voltage_1").val(calibrationData.ring_stop_voltage_1);
	$("#ring_increment_1").val(calibrationData.ring_increment_1);
	// $("#r1_current").val(calibrationData.r1_cur);
	$("#ring_start_voltage_2").val(calibrationData.ring_start_voltage_2);
	$("#ring_stop_voltage_2").val(calibrationData.ring_stop_voltage_2);
	$("#ring_increment_2").val(calibrationData.ring_increment_2);
	// $("#r2_current").val(calibrationData.r2_cur);
	$("#phase_start_voltage").val(calibrationData.phase_start_voltage);
	$("#phase_stop_voltage").val(calibrationData.phase_stop_voltage);
	$("#phase_increment").val(calibrationData.phase_increment);
	// $("#phase_current").val(calibrationData.phase_cur);
	$("#gain_start_current").val(calibrationData.gain_start_current);
	$("#gain_stop_current").val(calibrationData.gain_stop_current);
	$("#gain_increment").val(calibrationData.gain_inc);
	// $("#gain_current").val(calibrationData.gain_cur);
	$("#start_temperature").val(calibrationData.start_temperature);
	$("#stop_temperature").val(calibrationData.stop_temperature);
	$("#temp_increment").val(calibrationData.temp_inc);
	// $("#temp_current").val(calibrationData.temp_cur);
	$("#detector").val(calibrationData.detector);
	// $("#location").val(calibrationData.location);
	$("#soa_start").val(calibrationData.soa_start);
	$("#soa_stop").val(calibrationData.soa_stop);
	$("#soa_inc").val(calibrationData.soa_inc);
	// $("#soa_current").val(calibrationData.soa_current);
	if (platform.startsWith('Win')) {
		$("#location").val("C:\\Downloads\\filename.csv");
	// Windows
	// console.log('This site is being viewed on Windows');
	} else if (platform.startsWith('Mac')) {
		$("#location").val("home\\Downloads\\filename.csv");
	// macOS
	// console.log('This site is being viewed on macOS');
	} else if (platform.startsWith('Linux')) {
		$("#location").val("home\\Downloads\\filename.csv");
	// Linux
	// console.log('This site is being viewed on Linux');
	} else {
	// Other platform
	// console.log('This site is being viewed on an unknown platform');
	}
})
// function browseResult(e){
// 	var theFiles = e.target.files;
//     var relativePath = theFiles[0].webkitRelativePath;
//     var folder = relativePath.split("/");
//     alert(folder[0]);
// }
// getDir()
// async function getDir() {
// 	JFileChooser chooser = new JFileChooser();
// 	chooser.setCurrentDirectory(new java.io.File("."));
// 	chooser.setDialogTitle("select folder");
// 	chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// 	chooser.setAcceptAllFileFilterUsed(false);
//   }

function checkNegative(e){
	const fieldValue = e.target.value
  if (isNaN(fieldValue)) {
    e.target.value = '';
  } else {
    console.log('Valid input:', fieldValue);
  }
}
$("#restore-cali-btn").click(()=>{
	let parameter = {url : "../cgi/cgi_RestoreDefaultSettings.py", data : {requestType : "restore_calibration"}};
	$.ajax({
		url : parameter.url,
		type : "get",
		data : parameter.data,
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		success: function (response) {
			loadCalibrationData()
			showModal('Success', response.response);
		}
	})
})