// Page Description
// loadSlider() call from setup.js and take parameter sliderobj,sliderId,slidersetupValueId,min value,max value, width of slider
// loadSlider() width of slider from constant.js file

moduleControlParameters = [{
	moduleType: "temperature",
	url: "../cgi/cgi_TECManager.py",
	data: {
		requestType: "read_TEC"
	}
},
{
	moduleType: "currentController",
	url: "../cgi/cgi_IDriveManager.py",
	data: {
		requestType: "read_idrive",
	}
},
];

function BindIdriveData() {
	iDriveData.forEach(function (data, index) {
		if (data.set_current == null)
			iDriveData[index].set_current = 0;

		if (data.state == 0)
			$("#iDrive_State_" + index).attr("src", "../images/redLed.png");
		else if (data.state == 1)
			$("#iDrive_State_" + index).attr("src", "../images/greenLed.png");
		else
			$("#iDrive_State_" + index).attr("src", "../images/warningLed.png");

		$("#iDrive_CrReading_" + index).text(data.get_current);
		if (data.set_on_off_state == 1)
			$("#iDrive_Switch_" + index).prop("checked", true);
		else
			$("#iDrive_Switch_" + index).prop("checked", false);

		$("#iDrive_Setvalue_" + index).val(data.set_current);

		$("#iDrive_Setvalue_" + index).change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			eval("iDrive_Slider_Obj_" + index).slider.setValues(value, data.set_current_limit);
			outOffRange(data.set_min_current, data.set_current_limit, value)
			idriveId.push(data.id);
		});

		$("#iDrive_Switch_" + data.id).change(function () {
			idriveId.push(data.id);
		});

		if (eval("iDrive_Slider_Obj_" + index).slider != undefined)
			eval("iDrive_Slider_Obj_" + index).slider.setValues(data.set_current, data.set_current_limit);
	});
}

function BindDemuxMapData(set) {
	demuxMapData.forEach(function (d, index) {
		if (set == 0 || set == 1) {
			$("#Demux_Setvalue_" + index).val(d.set_demux_power);
			$("#Demux_Switch_" + index).prop("checked", d.set_on_off_state == 1 ? true : false);
			$("#Demux_Setvalue_" + index).change(function () {
				var value = parseFloat(parseFloat($(this).val()).toFixed(2));
				eval("Demux_Slider_Obj_" + index).slider.setValues(value, d.get_max_Demux_power);
				outOffRange(d.get_demux_power, d.get_max_Demux_power, value)
			});
		}
	});
}

function BindCombData(set) {
	$("#allCurrentController").html("");

	opticalFrequencyCombData.forEach(function (d, index) {
		// let disabledClass = d.state != 0 ? "disabled-link" : "";
		// let disabledAttr = d.state != 0 ? "style='pointer-events:none;opacity:0.6;cursor:not-allowed;'" : "";

		let laserStatus = d.state == 2 ? "Laser Disconnected" : "Laser Connected";
		let tecStatus = d.tecState == 1 ? "TEC Disconnected" :  "TEC Connected";
		let laserBackground = d.state == 2 ? "background: #ffefef;" : d.tecState == 1 ? "background: #ffefef;" : "";
		let laserColor = d.state == 2 ? "#ff0000"  : "green";
		let tecColor = d.tecState == 1 ? "#ff0000" :  "green";
		let disableButton = d.state != 0 ? "disabled" : d.tecState != 0 ? "disabled" : d.set_on_off_state == 0 ? "disabled" : "";
		let disableOnOff = d.state != 0 ? "disabled" : d.tecState != 0 ? "disabled" : "";

		let currentData = `<a id="laser-tab${index + 1}" class="third-level-child accordion-head" href="javascript:void(0);">Laser${index + 1} Current - <span style="color : ${laserColor};font-size: 12px;">${laserStatus}</span> - <span style="color : ${tecColor};font-size: 12px;">${tecStatus}</span></a>
			<div class="third-level-content tab-level-content variable-optical mb-2" style="${laserBackground}">
				<ul class="" style="list-style-type:none">
				<div class="row tempStatusDivs">
						<div class="col-lg-6">
							
						</div>
						<div class="col-lg-6 justify-content-center">
							<div class="pull-right" style="margin-left: -24px;background: #bdffd2ff;padding: 2px;border-radius: 5px;">
								<span>Prev Laser Value: </span>
								<span id="laser-reading${index + 1}"> ${d.prev_current} </span>
								<span>mA</span>
							</div>
						</div>
					</div>
					<div class="row colfixone">
						<div class="col-xl-3 col-md-3">
							<span class="light-color">Current Control (mA)</span>
						</div>
						<div class="col-xl-5 col-md-5 mt-xl-0 mb-xl-0 mtBEq" >
							<div class="slider-container" style="margin-left : -10px">
								<input type="text" id="current-controller-slider${index + 1}"
									class="discreteSlider slider" style="display:none" />
							</div>
						</div>
						<div class="col-xl-2 col-md-2 col-sm-10">
							<div class="form-inline">
								<div class="form-group">
									<label for="setValue">Set Value</label>
									<input type="number" id="current-controller-setvalue${index + 1}" value=""
										class="currentSetValue form-control common-input-field mx-sm-3" ${disableButton}>
								</div>
							</div>
						</div>
						<div class="col-xl-1 col-md-1 col-sm-2">
							<label id="currentController-switch-off${index + 1}"
								class="tooltipBtn toggleSwitch large switchFix">
								<input type="checkbox" id="current-turn-on-off${index + 1}"  data-id="${index + 1}" class="currentToggle" ${disableOnOff}>
								<span>
									<span>OFF</span>
									<span>ON</span>
								</span>
								<a></a>
								<p class="tooltiptext"></p>
							</label>
						</div>
					</div>

					
				</ul>
			</div>`

		$("#allCurrentController").append(currentData);

		$("#allCurrentController").off('click', 'a.third-level-child').on('click', 'a.third-level-child', function (e) {
			e.preventDefault();
			var $this = $(this);

			$this.toggleClass('icon');
			$this.next().toggleClass('show-level');

			$(".customClass").animate({
				scrollTop: ($this.offset().top) - $(".customClass").offset().top + $(".customClass").scrollTop()
			}, 1000);
		});

		if (d.set_on_off_state == 1)
			$(`#current-turn-on-off${index + 1}`).prop("checked", true);
		else
			$(`#current-turn-on-off${index + 1}`).prop("checked", false);
	})

	opticalFrequencyCombData.forEach(function (data, index) {
		window['currentControllerSliderObj' + (index + 1)] = {};
		$(`#laser-tab${index + 1}`).click(function () {
			if ($(`#current-controller-slider${index + 1}`).next().length == 0) {
				setTimeout(function () {
					loadSlider(eval(`currentControllerSliderObj${index + 1}`), `#current-controller-slider${index + 1}`, `#current-controller-setvalue${index + 1}`, data.set_min_current, data.set_current_limit, data.set_current, generalSliderWidthLVL1, false, 1, true);
					if (data.state != 0 || data.tecState != 0 || data.set_on_off_state == 0) {
						disableSlider(`#current-controller-slider${index + 1}`);
					}
				}, 1);
			}
			// $("#optical-comb-tab").animate({
			// 	scrollTop: 10 // Scroll up by 10 pixels
			// }, 1500);

		});
		$(`#current-controller-setvalue${index + 1}`).change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			let currentControllerSliderObj = eval(`currentControllerSliderObj${index + 1}`);
			currentControllerSliderObj.slider.setValues(value, data.set_current_limit)
			outOffRange(data.set_min_current, data.set_current_limit, value)
		});
	})

}

function saveRFSynthData(url, requestType, id, frequency, power, onoffState, showMsg) {
	$.ajax({
		type: "Get",
		url: url,
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: requestType,
			id: id,
			set_Frequency: frequency,
			set_Power: power,
			OnOffState: onoffState
		},
		success: function (response) {
			$('.loaderDiv').css('display', 'none');
			if (showMsg)
				showModal('Success', response.description);
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		}
	});
}

function saveData(url, requestType, id, name, setValue, turnOnOffState, showMsg) {
	if (setValue == "")
		setValue = 0;

	$.ajax({
		type: "Get",
		url: url,
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: requestType,
			id: id,
			name: name,
			set_on_off_state: turnOnOffState,
			set_current: setValue
		},
		success: function (response) {
			if (showMsg) {
				if (response?.status == 'fail') {
					showModal('Error', response.description);
					$('.loaderDiv').css('display', 'none');
					loadModuleControlData();
				}
				else {
					showModal('Success', response.description);
					setTimeout(() => {
						$("#myModal").modal("hide");

					}, autoClose)
					setTimeout(() => {
						loadModuleControlData();
					}, 1000)

				}
			}
			else {
				if (response?.status == 'fail') {
					showModal('Error', response.description);
					$('.loaderDiv').css('display', 'none');
				}
				else {
					$('.loaderDiv').css('display', 'none');
					showModal('Success', "Updated successfully ");
				}
			}
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		}
	});
}

function saveDemultiplexData(url, requestType, id, name, setvalue, turnOffState, demux_id, set_tone, showMsg) {
	if (setvalue == "")
		setvalue = 0;

	$.ajax({
		type: "Get",
		url: url,
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: requestType,
			id: id,
			name: name,
			set_on_off_state: turnOffState,
			set_power: setvalue,
			lut_id: demux_id,
			set_tone: set_tone
		},
		success: function (response) {
			console.log(response.status + "," + response.description);
			if (showMsg)
				showModal(response.status, response.description);
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		}
	});
}


function loadModuleControlData() {
	return new Promise(function (resolve, reject) {
		let i = 1;
		moduleControlParameters.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) {
					switch (parameter.moduleType) {
						case "temperature":
							techData = response;
							BindTechData(techData);
							break;
						case "currentController":
							opticalFrequencyCombData = response;
							BindCombData(0);
							break;
					}
					$("#graph-water-mark").addClass("d-none");
					$(".main-tab-content").removeClass("d-none");
					$('.loaderDiv').css('display', 'none');
					if (moduleControlParameters.length == i) {
						stopAllTemperatureIntervals()
						resolve()
					}
					else {
						++i;
					}
				},
				error: function (ex) {
					// $("#test").html(ex.responseText)
					if (moduleControlParameters.length == i) {
						reject(ex)
					}
					else {
						++i;
					}
				}
			});
		});
	})
	// if ($("#demo_dr_demultiplexer_0").val() == -1 || $("#demo_dr_demultiplexer_1").val() == -1 || $("#demo_dr_demultiplexer_2").val() == -1 || $("#demo_dr_demultiplexer_3").val() == -1) {
	// 	$("#updateView").prop("disabled", true);
	// }
}

function BindTechData(techData) {
	$("#tecAllData").html("");
	techData.forEach(function (data, index) {
		// let disabledClass = data.state != 0 ? "disabled-link" : "";
		// let disabledAttr = data.state != 0 ? "style='pointer-events:none;opacity:0.6;cursor:not-allowed;'" : "";
		let tecStatus = data.state == 1 ? "TEC Disconnected" :  "TEC Connected";
		let laserStatus = data.idriveState == 2 ? "Laser Disconnected" : "Laser Connected";
		let tecBackground = data.state == 1 ? "background: #ffefef;" : data.idriveState == 2 ? "background: #ffefef;" : "";
		let tecColor = data.state == 1 ? "#ff0000" :  "green";
		let laserColor = data.idriveState == 2 ? "#ff0000" : "green";
		let disableButton = data.state != 0 ? "disabled" : data.idriveState != 0 ? "disabled" : "";

		let tecData = `<a id="general-tab${index + 1}" data-tec-id="${data.Id}" data-index="${index + 1}" class="third-level-child accordion-head" href="javascript:void(0);">TEC ${index + 1} - <span style="color : ${tecColor}; font-size: 12px;">${tecStatus}</span> - <span style="color : ${laserColor};font-size: 12px;">${laserStatus}</span> </a>
			<div class="third-level-content tab-level-content variable-optical mb-2" style="${tecBackground}">
				<ul class="" style="list-style-type:none">
					<div class="row tempStatusDivs">
						<div class="col-lg-6">
							<div>
								<img src='../images/TEC.png'></img>
								<img class="temp-state"></img>
								<span>TEC ON</span>
							</div>
							<div>
								<img src='../images/Temperature.png'></img>
								<img class="temp-state"></img>
								<span>Temperature Sensor</span>
							</div>
						</div>
						<div class="col-lg-6 justify-content-center">
							<div class="pull-right" style="margin-left: 40px;background: #bdffd2ff;padding: 2px;border-radius: 5px;" id="temp_div">
								<span>Temperature Reading: </span>
								<span id="temp-reading${index + 1}"> ${data.getCurrent} </span>
								<span>&#8451;</span>
							</div>
						</div>
					</div>
					<div class="row separator-sm">
						<input id="temp-id${index + 1}" type="hidden" value="${data.Id}" />
						<div class="col-xl-3 col-md-3  d-flex">
							<img class="temp-image" src='../images/Temperature.png'></img>
							<div class="indicator-light-span"></div>
							<span><b>Temperature Control (&#8451;)</b></span>
						</div>
						<div class="col-xl-5 col-md-5" >
							<div class="slider-container" style="margin-left : -10px">
								<input type="text" id="general-slider${index + 1}" class="slider"
									style="display:none" ${disableButton} />
							</div>
						</div>
						<div class="col-xl-2 col-md-2 col-sm-10 ">
							<div class="form-inline">
								<div class="form-group">
									<label for="setValue">Set Value</label>
									<input type="number" id="general-setvalue${index + 1}" value=""
										class="form-control common-input-field mx-sm-3 " ${disableButton}>
								</div>
							</div>
						</div>
						<div class="col-xl-2 col-md-2  col-sm-2 d-flex justify-content-between">
							<!--<button type="button" class="btn">Turn Off</button>-->
							<div>
								<label
									class="tooltipBtn toggleSwitch large switchFix">
									<input type="checkbox" id="temp-turn-on-off${index + 1}" class="" ${disableButton}>
									<span>
										<span>OFF</span>
										<span>ON</span>
									</span>
									<a></a>
									<p class="tooltiptext"></p>
								</label>
							</div>
							<div style="margin-top: -12px;">
								<button type="button"
									class="float-left save-btn btn btn-primary"
									value="temperature${index + 1}" ${disableButton}>Save</button>
							</div>
						</div>
					</div>
				</ul>
			</div>`
		$("#tecAllData").append(tecData);

		$("#tecAllData").off('click', 'a.third-level-child').on('click', 'a.third-level-child', function (e) {
			e.preventDefault();
			var $this = $(this);

			if ($this.hasClass('disabled-link')) return;

			let tecId = $this.data("tec-id");
			let index = $this.data("index");

			let $content = $this.next(".third-level-content");

			$this.toggleClass('icon');
			$content.toggleClass('show-level');

			if ($content.hasClass('show-level')) {
				getCurrentTemperature(tecId, `#temp-reading${index}`, true);
			}
			else {
				stopTemperatureIntervalById(tecId)
			}

			$(".customClass").animate({
				scrollTop: ($this.offset().top) - $(".customClass").offset().top + $(".customClass").scrollTop()
			}, 1000);
		});
	})

	techData.forEach(function (data, index) {
		window['tempSliderObj' + (index + 1)] = {};
		$(`#general-tab${index + 1}`).click(function () {
			// getCurrentTemperature(data.Id, `#temp-reading${index + 1}`);
			if ($(`#general-slider${index + 1}`).next().length == 0) {
				setTimeout(function () {
					loadSlider(eval(`tempSliderObj${index + 1}`), `#general-slider${index + 1}`, `#general-setvalue${index + 1}`, data.setMinTemp, data.setMaxTemp, data.setTemp, generalSliderWidthLVL1, false, 0.01, false);
					readJsonData(moduleControlParameters[0].moduleType, techData);
					if (data.state != 0 || data.idriveState != 0) {
						disableSlider(`#general-slider${index + 1}`);
					}
				}, 1);
			}
		});

		$(`#general-setvalue${index + 1}`).change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			let objTec = eval(`tempSliderObj${index + 1}`);
			objTec.slider.setValues(value, data.setMaxTemp);
			outOffRange(data.setMinTemp, data.setMaxTemp, value);
		});
	})
}


function getCurrentTemperature(id, elementId, firstTime) {
	// Clear any previous interval for this TEC
	if (temperatureIntervals[id]) {
		temperatureIntervals[id]();
	}
	let isFirstCall = firstTime;

	const fetchTemperature = () => {
		let onOffState = $("#temp-turn-on-off" + id).prop("checked") ? 1 : 0;

		// Call API only if first time or TEC is ON
		if (isFirstCall || onOffState) {
			$.ajax({
				type: "GET",
				url: "../cgi/cgi_TECManager.py",
				contentType: "application/json",
				dataType: "json",
				headers: { "Access-Control-Allow-Origin": "*" },
				data: {
					requestType: "get_current_temperature",
					id: id
				},
				success: function (response) {
					if (response.status === "fail") {
						if (isFirstCall) {
							showModal("Error", response.description);
						}
					} else {
						if (parseInt(response.getCurrent) === -1) {
							$("#tem_div").css({ "background": "#ffbdbd" });
						}
						$(elementId).html(response.getCurrent);
						$("#temp-turn-on-off" + id).prop(
							"checked",
							response.state > 0
						);
					}
					isFirstCall = false
				},
				error: function () {
					$(elementId).html("0");
					isFirstCall = false;
				}
			});

		}
	};

	if (isFirstCall) {
		fetchTemperature();
	}

	const intervalId = setInterval(fetchTemperature, 10000);

	temperatureIntervals[id] = () => clearInterval(intervalId);

	return temperatureIntervals[id];
}


function stopAllTemperatureIntervals() {
	Object.values(temperatureIntervals).forEach(stop => stop());
	Object.keys(temperatureIntervals).forEach(key => delete temperatureIntervals[key]);
}

// stop one specific id
function stopTemperatureIntervalById(id) {
	if (temperatureIntervals[id]) {
		temperatureIntervals[id]();
		delete temperatureIntervals[id];
	}
}

$(document).on("click", ".save-btn", function () {
	$('.loaderDiv').css('display', 'block');
	var btnValue = $(this).val();
	if (btnValue.startsWith("temperature")) {
		var index = btnValue.replace("temperature", "");
		const tec_state = $("#temp-turn-on-off" + index).prop("checked") ? 1 : 0
		if (tec_state == 0) {
			let laser_data = opticalFrequencyCombData.filter((item) => item.id == parseInt($("#temp-id" + index).val()));
			if (laser_data.length > 0) {
				let lOnOffState = laser_data[0]?.set_on_off_state;
				let lvalue = laser_data[0]?.set_current;
				if (lOnOffState != 0) {
					const payload = {
						id: laser_data[0].id,
						set_current: 0,
						set_on_off_state: 0
					}
					resetCurrentControllerData(payload)
				}
			}
		}

		saveData(
			"../cgi/cgi_TECManager.py",
			"update_TEC",
			$("#temp-id" + index).val(),
			"Temperature Control",
			$("#general-setvalue" + index).val(),
			tec_state,
			true
		);

		return;
	}

	switch ($(this).val()) {
		case "currentController":
			saveOpticalCombData(true);
			break;

	}
});

function resetCurrentControllerData(data) {
	let isShowMsg = true
	showModal('Warning', `Reseting Laser${data.id}`);
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_IDriveManager.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "update_i_drive",
			id: data.id,
			set_current: data.set_current,
			set_on_off_state: data.set_on_off_state
		},
		success: function (response) {
			if (isShowMsg) {
				if (response.status == "fail") {
					showModal('Error', response.description);
				}
				else {
					loadModuleControlData();
				}
			}
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		},

	});
}

$(document).ready(function () {

	loadModuleControlData().then(function () {
		//cancel
		$("#cancel-btn").click(function () {
			let tecChanges = [];
			let currentChanges = [];
			techData.forEach(function (data, index) {
				let setTemp = $(`#general-setvalue${index + 1}`).val();
				let onOffState = $(`#temp-turn-on-off${index + 1}`).prop("checked") == true ? 1 : 0;
				if (!setTemp) {
					return
				}
				if (setTemp != data.setTemp || onOffState != data.onOffState) {
					tecChanges.push({
						id: index + 1,
						setTemp: data?.setTemp,
						onOffState: data?.onOffState
					});
				}
			});

			opticalFrequencyCombData.forEach(function (data, index) {
				let set_current = $(`#current-controller-setvalue${index + 1}`).val();
				let onOffState = $(`#current-turn-on-off${index + 1}`).prop("checked") == true ? 1 : 0;
				if (!set_current) {
					return
				}
				if (set_current != data.set_current || onOffState != data.set_on_off_state) {
					currentChanges.push({
						id: data.id,
						set_current: data?.set_current,
						onOffState: data?.set_on_off_state,
						set_current_limit: data?.set_current_limit
					});
				}
			});


			if (tecChanges.length > 0) {
				showModal("Alert!", "Changes Reversed");
				tecChanges.forEach(function (data, index) {
					if ($(`#general-slider${data.id}`).next().length > 0) {
						readJsonData(moduleControlParameters[0].moduleType, techData);
						let objTec = eval(`tempSliderObj${data.id}`)
						objTec.slider.setValues(data.setTemp, data.setMaxTemp);

					}
				})
			}

			if (currentChanges.length > 0) {
				showModal("Alert!", "Changes Reversed");
				currentChanges.forEach(function (data, index) {
					if ($(`#current-controller-slider${data.id}`).next().length > 0) {
						readJsonData(moduleControlParameters[1].moduleType, opticalFrequencyCombData);
						let objComb = eval(`currentControllerSliderObj${data.id}`)
						objComb.slider.setValues(data.set_current, data.set_current_limit);
					}
				})
			}


			if (tecChanges.length == 0 && currentChanges.length == 0) {
				showMsg = true
				showModal("Alert!", "No Changes Detected")
			}
		});

		$("#restore-module-btn").click(() => {
			let parameter = { url: "../cgi/cgi_RestoreDefaultSettings.py", data: { requestType: "restore_module" } };
			$.ajax({
				url: parameter.url,
				type: "get",
				data: parameter.data,
				contentType: 'application/json',
				dataType: 'json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				success: function (response) {
					showModal('Success', response.response);
					loadModuleControlData()
				}
			})
		})


		$(".accordion-head").click(function (e) {
			e.preventDefault();
			var $this = $(this);
			if ($this.hasClass('icon') == true) {
				$(".customClass").animate({
					scrollTop: ($this.offset().top) - $(".customClass").offset().top + $(".customClass").scrollTop()
				}, 1000);
			}
		})
	})
})

$("#tecTestInput").change(function () {
	let isChecked = $(this).prop("checked");
	let data = isChecked ? 1 : 0;

	if (data) {
		$(".loaderDiv").css("display", "block");

		// Call API after a small delay to let UI update
		setTimeout(() => {
			$.ajax({
				type: "GET",
				url: "../cgi/cgi_TecCurrent_Test.py",
				async: true,
				contentType: 'application/json',
				dataType: 'json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				data: {
					requestType: "tecTest"
				},
				success: function (response) {
					if (response.status == "fail") {
						showModal("Error", response.description || response.result);
					}
					else {
						
						let data = response?.result;

						let html = `
							<b>${response.description}</b><br>
							<table border="1" class="table-sm mt-2" cellpadding="6" cellspacing="0" style="border-collapse:collapse; width:100%;">
								<thead>
									<tr>
										<th>Device No.</th>
										<th>TEC</th>
										<th>Laser</th>
									</tr>
								</thead>
								<tbody>
						`;

						for (let id in data) {
							let tec_color = data[id].tec === 0 ? "green" : "red";
							let laser_color = data[id].laser === 0 ? "green" : "red";

							let tec_status = data[id].tec_text;       // connected/disconnected text you already have
							let laser_status = data[id].laser_text;

							html += `
								<tr>
									<td><b>${id}</b></td>
									<td style="color:${tec_color}; font-weight:bold;">${tec_status}</td>
									<td style="color:${laser_color}; font-weight:bold;">${laser_status}</td>
								</tr>
							`;
						}

						html += `
								</tbody>
							</table>
						`;


						showModal(
							"Alert!!",
							html,
							1000000000
						);
					}

				},
				error: function (xhr) {
					showModal('Error', 'Failed to start TEC Test.');
				},
				complete: function () {
					setTimeout(function () {
						$(".loaderDiv").hide();
						$("#tecTestInput").prop("checked", false);
					}, 1000);
				}
			});
		}, 100); // short delay (100ms) ensures toggle UI updates first
	}
});


function disableSlider(sliderID) {
	$(sliderID).next('.rs-container').css({
		"pointer-events": "none",
		"opacity": "0.5",
		"user-select": "none"
	});

	$(sliderID).attr("tabindex", "-1");

}

function enableSlider(sliderID) {
	$(sliderID).next('.rs-container').css({
		"pointer-events": "auto",
		"opacity": "1",
		"user-select": "auto"
	});

	$(sliderID).attr("tabindex", "0");
}

$(document).on('change', '.currentToggle', function () {
	let index = $(this).data('id');
	let isChecked = $(this).is(':checked');
	if(isChecked){
		enableSlider(`#current-controller-slider${index}`);
		$(`#current-controller-setvalue${index}`).attr("disabled", false);
	}
	else{
		disableSlider(`#current-controller-slider${index}`);
		$(`#current-controller-setvalue${index}`).attr("disabled", true);
	}
	let laserData = opticalFrequencyCombData.filter((item) => item.id == parseInt(index))?.[0];
	let currentControllerSliderObj = eval(`currentControllerSliderObj${index}`);
	currentControllerSliderObj.slider.setValues(isChecked ? laserData.prev_current : 0, laserData.set_current_limit)
});
