var isSetUnprotectedMode = true;
var isDemoSetUnprotectedMode = true;
var showMsgBox = false;
let tempSliderObj = {};
let tempSliderObj1 = {};
let centralWavelengthSliderObj = {};
let centralWavelengthSliderObj1 = {};
let combFrequencySliderObj = {};
let combFrequencySliderObj1 = {};
let demoCentralWavelengthSliderObj = {};
let demoCombFrequencySliderObj = {};
let rfSynthFqSliderObj = {};
let rfSynthPwSliderObj = {};
let demuxCombo1Obj = {};
let demuxCombo2Obj = {};
let demuxCombo3Obj = {};
let demuxCombo4Obj = {};
let iDrive_Slider_Obj_0 = {};
let iDrive_Slider_Obj_1 = {};
let iDrive_Slider_Obj_2 = {};
let iDrive_Slider_Obj_3 = {};
let iDrive_Slider_Obj_4 = {};
let iDrive_Slider_Obj_5 = {};
let iDrive_Slider_Obj_6 = {};
let iDrive_Slider_Obj_7 = {};
let iDrive_Slider_Obj_8 = {};
let iDrive_Slider_Obj_9 = {};
let iDrive_Slider_Obj_10 = {};
let iDrive_Slider_Obj_11 = {};
let iDrive_Slider_Obj_12 = {};
let iDrive_Slider_Obj_13 = {};
let Demux_Slider_Obj_0 = {};
let Demux_Slider_Obj_1 = {};
let Demux_Slider_Obj_2 = {};
let Demux_Slider_Obj_3 = {};
let Demo_Demux_Slider_Obj_0 = {};
let Demo_Demux_Slider_Obj_1 = {};
let Demo_Demux_Slider_Obj_2 = {};
let Demo_Demux_Slider_Obj_3 = {};
let calibrationWaveSliderObj = {};
let calibrationFreqSliderObj = {};

let Debug_Slider_1 = {};
let Debug_Setvalue_1 = {};
let Debug_Slider_2 = {};
let Debug_Setvalue_2 = {};
let Debug_Slider_3 = {};
let Debug_Setvalue_3 = {};
let Debug_Slider_4 = {};
let Debug_Setvalue_4 = {};
let Debug_Slider_5 = {};
let Debug_Setvalue_5 = {};
let Debug_Slider_6 = {};
let Debug_Setvalue_6 = {};
let Debug_Slider_7 = {};
let Debug_Setvalue_7 = {};
let Debug_Slider_8 = {};
let Debug_Setvalue_8 = {};
let Debug_Slider_9 = {};
let Debug_Setvalue_9 = {};
let Debug_Slider_10 = {};
let Debug_Setvalue_10 = {};

var isIDriveValChange = false
isSetUnprotectedMode = true;
const temperatureIntervals = {};



let idriveId = [];
let rfSynthId = [];

var mymodal = $('#myModal');
mymodal.find(".modal-body").addClass("scrollContainerModal");
var opticalCombSwitchId = "#wavelength-turn-on-off";
var demoOpticalCombSwitchId = "#demo-wavelength-turn-on-off";
var techData = null;
var opticalFrequencyCombData = null;
var rfSynthData = null;
var iDriveData = null;
var combToneData = null;
var demuxMapData = null;
var demoDemuxMapData = null;
var demoCombToneData = null;
var combtone1, combtone2, combtone3, combtone4 = -1;
var demo_combtone1, demo_combtone2, demo_combtone3, demo_combtone4 = -1;


var commonOpticalCombId = "";

// data for idac_vdac
var iDAC_VDAC_data = null

var isCllicked = false;
var parameters = {};
var url = String.empty;
var moduleControlData = [];
var demoModeData = [];
var connectionSettings = [];
var moduleControlParameters = [];
var isReverseSSHConnected = false;
var reverseSShData = {};
var ethernetData = {};


function outOffRange(minValue, maxValue, setValue) {
	if (setValue > maxValue || setValue < minValue) {
		swal("Warning", "out of range", "warning");
	}
}


function loadSlider(sliderObj, sliderID, sliderSetupValueID, min, max, setValue, width, isIDrive, step, isOpticalComb, isDemoIDrive, id, isRfSynth, isDebug = false) {
	let values = {
		min: min,
		max: max
	}
	sliderObj.slider = new rSlider({
		target: sliderID,
		values: values,
		step: step,
		range: true,
		scale: true,
		labels: false,
		width: width,
		idriveId: id,
		isRfSynth: isRfSynth,
		isIDrive: isIDrive,
		isOpticalComb: isOpticalComb,
		onChange: function (vals) {
			min = vals.split(",")[0];
			if (isOpticalComb)
				min = parseInt(min);
			else
				min = parseFloat(min).toFixed(2);
			$(sliderSetupValueID).val(min);
		}
	});
	sliderObj.slider.setValues(setValue, max);


	$($('div[data-dir="right"]')).css("display", "none");
	// if (!isDebug) {
	// 	$(".rs-scale").children().css("display", "none");
	// }
	// $(".rs-scale").css("right", 0);
	// console.log($(".rs-scale").children(), $(".rs-scale").children().last(), "child");
	// $(".rs-scale").children().last().css("float", "right");
	if (isIDrive && step == 0.01 || isIDrive && step == 0.001) {
		// if (isIDrive) {
		var protectModeVar = false;
		if (isDemoIDrive)
			var switchID = demoOpticalCombSwitchId;
		else
			var switchID = opticalCombSwitchId;

		$(sliderObj.slider.conf.target).nextAll().find(".rs-pointer").mousedown(function (e) {
			commonOpticalCombId = switchID;
			if (switchID == "#demo-wavelength-turn-on-off")
				protectModeVar = isDemoSetUnprotectedMode;
			else
				protectModeVar = isSetUnprotectedMode;

			protectModeVar = true

			if (protectModeVar == false) {
				if ($(switchID).prop("checked") == true) {
					$(".state-box-layout").fadeIn();
					$("body").css("overflow", "hidden");
				} else {
					$(".warning-box-layout").fadeIn();
					$("#warning-password").focus();
					$("body").css("overflow", "hidden");
				}
			}
		});
	}
	// to add slider user validation on normal sliders
	// else if (isOpticalComb){
	// 	$(sliderObj.slider.conf.target).nextAll().find(".rs-pointer").mousedown(function (e) {
	// 		if (isSetUnprotectedMode == false) {
	// 				$(".warning-box-layout").fadeIn();
	// 				$("#warning-password").focus();
	// 				$("body").css("overflow", "hidden");
	// 		}
	// 	});
	// }
}

function readJsonData(connectionType, data) {
	switch (connectionType) {
		case "ethernet":
			ethernetData = data[0];
			data.forEach(function (d) {
				$("#IPaddress").val(d.ip_addr);
				$("#subNetMask").val(d.netmask);
				$("#defaultGetway").val(d.gateway);
				$("#DNSServer").val(d.dns);
				$("#ethernetCheckButton").prop("checked", d.enabled == 1 ? true : false);
			});
			break;
		case "serial":
			data.forEach(function (d) {
				$("#BAUDRate").val(d.baud_rate);
				$("#Parity").val(d.parity);
				$("#DataBits").val(d.data_bits);
				$("#flowControl").val(d.flow_control);
				$("#serialCheckButton").prop("checked", d.enabled == 1 ? true : false);
			});
			break;
		case "remote_storage":
			data.forEach(function (d) {
				$("#rs-share").val(d.share);
				$("#rs-user").val(d.user);
				$("#rs-password").val(d.password);
				$("#protocol").val(d.protocol);
				$("#remoteButton").prop("checked", d.enabled == 1 ? true : false);
			});
			break;
		case "remote":
			data.forEach(function (d) {
				$("#remoteControlID").val(d.id);
				// $("#remoteControlEnable").prop("checked", d.enabled == 1 ? true : false);
				$("input[name='remoteControlEnable']").each(function () {
					if ($(this).attr('value') == (d?.enabled ? "yes" : "no")) {
						$(this).prop('checked', true);
					}
				});
			});
			break;
		case "email":
			emailResponse = data
			data.forEach(function (d) {
				$("#recipientEmail").val(d.out_server);
				$("#senderEmail").val(d.in_server);
				$("#smtpServer").val(d.smtp_server);
				$("#portNumber").val(d.port_number);
				$("#password").val(d.pw);
				if (d.authentication == "true")
					$("#authenticationCheck").prop('checked', true);
				else
					$("#authenticationCheck").prop('checked', false);


				if (d.alert_msg == "true") {
					$("#alertMessagesON").prop('checked', true);
					const parts = d.level.split(',');
					for (var i = 0; i < parts.length; i++) {
						if (parts[i] == "INFO")
							$("#InfoMessagesON").prop('checked', true);
						else if (parts[i] == "WARNING")
							$("#warningMessagesON").prop('checked', true);
						else if (parts[i] == "ALERT")
							$("#alertMessages").prop('checked', true);
					}
				} else {
					$("#alertMessagesON").prop('checked', false);
					$("#InfoMessagesON").prop('checked', false);
					$("#warningMessagesON").prop('checked', false);
					$("#alertMessages").prop('checked', false);
				}
			});
			break;
		case "temperature":

			data.forEach(function (d, index) {
				if (d.onOffState == 1)
					$(`#temp-turn-on-off${index + 1}`).prop("checked", true);
				else
					$(`#temp-turn-on-off${index + 1}`).prop("checked", false);
			})

			break;
		case "currentController":
			data.forEach(function (d, index) {
				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);
			})
			break;
		case "Password_hidden":
			// console.log(data[0].type)
			let type = $("#rs-password");
			let typeValue = data[0]?.type == "Yes" ? "password" : "text";
			type.attr("type", typeValue);
			if (data[0]?.type == 'Yes') {
				$("#togglePassword").show()
				$("#hidetogglePassword").hide()
			}
			else {
				$("#togglePassword").hide()
				$("#hidetogglePassword").show()
			}
			break;
		case "read_enable_ssh":
			$("input[name='rbEnSSH']").each(function () {
				if ($(this).attr('value') == data?.enable_ssh) {
					$(this).prop('checked', true);
				}
			});
			$("#sshButton").prop("checked", data.enabled == 1 ? true : false);

			$('#sshButton').change(function () {
				const isChecked = $(this).is(':checked');
				$('input[name="rbEnSSH"]').prop('disabled', !isChecked).css('cursor', isChecked ? 'pointer' : 'auto');
			}).trigger('change');

			break;
		case "read_reverse_ssh":
			reverseSShData = data;
			$("input[name='enReverseSSH']").each(function () {
				if ($(this).attr('value') == data?.enable_reverse) {
					$(this).prop('checked', true);
				}
			});

			if (data?.enable_reverse == "yes") {
				$("#reverseSshConfig").show();
			}
			else {
				$("#reverseSshConfig").hide();
				$("#connectReverseSSH").attr("disabled", true);
				$("#connectReverseSSH").hide();
				$("#disconnectReverseSSH").hide();
				$("#cancelReverseSSH").hide();
			}
			$("#rs_remote_ip").val(data?.remote_ip),
				$("#rs_remote_port").val(data?.remote_port),
				$("#rs_remote_user").val(data?.username),
				$("#rs_local_port").val(data?.local_port),
				$("#key_file_name").html(data?.key_path).css({ "color": "green" })
			$("#rs_key_path").html(data?.file_content);
			readReverseSshStatus();

			$('#reverseSsh').change(function () {
				const isChecked = $(this).is(':checked');
				$('input[name="enReverseSSH"]').prop('disabled', !isChecked).css('cursor', isChecked ? 'pointer' : 'auto');
			}).trigger('change');

			break;
	}
}


function showModal(title, desc, auto_close = autoClose) {
	if (title == "Error") {
		$(".modal-header").css({
			"color": "#fff",
			"background-color": "#db4141"
		});
		$(".close").css({
			"color": "#fff"
		});
	}
	else if (title == "Warning") {
		$(".modal-header").css({
			"color": "#fff",
			"background-color": "#f0ad4e"
		});
		$(".close").css({
			"color": "#fff"
		});
	}
	else {
		$(".modal-header").css({
			"color": "#000",
			"background-color": "#fff"
		});
		$(".close").css({
			"color": "#000"
		});
	}
	mymodal.find('.modal-title').text(title);
	mymodal.find('.modal-body').html(desc).css({ "text-align": "center" });
	mymodal.modal('show');
	setTimeout(() => {
		mymodal.modal("hide")
		// $(".modal-header").css({
		// 	"color": "#000",
		// 	"background-color": "#fff"
		// });
		// $(".close").css({
		// 	"color": "#000"
		// });
	}, auto_close)

}

function BindDropdownCombToneData() {
	$("#dr_demultiplexer_0,#dr_demultiplexer_1,#dr_demultiplexer_2,#dr_demultiplexer_3").empty();
	$("#dr_demultiplexer_0,#dr_demultiplexer_1,#dr_demultiplexer_2,#dr_demultiplexer_3").append(new Option("Select", -1));
	combToneData.forEach(function (data) {
		$("#dr_demultiplexer_0,#dr_demultiplexer_1,#dr_demultiplexer_2,#dr_demultiplexer_3").append(new Option(data.tone + " , " + data.comb_central_wav, data.id));
	});
	combtone1 = demuxMapData[0].lut_id;
	combtone2 = demuxMapData[1].lut_id;
	combtone3 = demuxMapData[2].lut_id;
	combtone4 = demuxMapData[3].lut_id;

	if (combToneData.find(x => x.id === demuxMapData[0].lut_id)) {
		$("#dr_demultiplexer_0").val(demuxMapData[0].lut_id);
		$("#dr_demultiplexer_1 option[value='" + demuxMapData[0].lut_id + "'").remove();
		$("#dr_demultiplexer_2 option[value='" + demuxMapData[0].lut_id + "'").remove();
		$("#dr_demultiplexer_3 option[value='" + demuxMapData[0].lut_id + "'").remove();
	} else {
		$("#dr_demultiplexer_0").val(-1);
	}

	if (combToneData.find(x => x.id === demuxMapData[1].lut_id)) {
		$("#dr_demultiplexer_1").val(demuxMapData[1].lut_id);
		$("#dr_demultiplexer_0 option[value='" + demuxMapData[1].lut_id + "'").remove();
		$("#dr_demultiplexer_2 option[value='" + demuxMapData[1].lut_id + "'").remove();
		$("#dr_demultiplexer_3 option[value='" + demuxMapData[1].lut_id + "'").remove();
	} else {
		$("#dr_demultiplexer_1").val(-1);
	}

	if (combToneData.find(x => x.id === demuxMapData[2].lut_id)) {
		$("#dr_demultiplexer_2").val(demuxMapData[2].lut_id);
		$("#dr_demultiplexer_0 option[value='" + demuxMapData[2].lut_id + "'").remove();
		$("#dr_demultiplexer_1 option[value='" + demuxMapData[2].lut_id + "'").remove();
		$("#dr_demultiplexer_3 option[value='" + demuxMapData[2].lut_id + "'").remove();
	} else {
		$("#dr_demultiplexer_2").val(-1);
	}

	if (combToneData.find(x => x.id === demuxMapData[3].lut_id)) {
		$("#dr_demultiplexer_3").val(demuxMapData[3].lut_id);
		$("#dr_demultiplexer_0 option[value='" + demuxMapData[3].lut_id + "'").remove();
		$("#dr_demultiplexer_1 option[value='" + demuxMapData[3].lut_id + "'").remove();
		$("#dr_demultiplexer_2 option[value='" + demuxMapData[3].lut_id + "'").remove();
	} else {
		$("#dr_demultiplexer_3").val(-1);
	}
}

function saveOpticalCombData(isShowMsg) {
	let dataUpdated = []
	let tecToTurnOn = [];

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

		if (parseInt(data?.set_current) == parseInt(set_current) && data?.set_on_off_state == parseInt(set_on_off_state)) {
			return
		}
		dataUpdated.push({
			id,
			set_current,
			set_on_off_state
		})

	});

	if (dataUpdated.length == 0) {
		if (isShowMsg) {
			showModal('Info', 'No Changes Detected');
			$('.loaderDiv').css('display', 'none');
		}
		return
	}

	if (dataUpdated.length > 0) {
		dataUpdated.forEach(changed => {
			const tecItem = techData.find(t => t.Id === changed.id);
			if (tecItem && tecItem.onOffState !== 1) {
				tecToTurnOn.push(tecItem);
			}
		});
	}

	if (tecToTurnOn.length > 0) {
		let tecList = tecToTurnOn
			.map(
				(t) =>
					`TEC : ${t.Id}`
			)
			.join("<br>");
		showConfirmModal(
			"TEC Update Confirmation",
			`TEC should be turned ON before Laser update !!.<br>${tecList}<br>Do you wish to turn ON TEC ?`,
			async () => {
				await updateTecAndOptical(tecToTurnOn, dataUpdated, isShowMsg);
			},
			() => {
				showModal("Info", "TEC and Laser Update Cancelled.");
				$('.loaderDiv').css('display', 'none');
				resetLaserData()
			}
		);

	} else {
		updateTecAndOptical([], dataUpdated, isShowMsg);
	}

}

function resetLaserData() {
	let currentChanges = [];
	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 (currentChanges.length > 0) {
		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);
			}
		})
	}
}

function showConfirmModal(title, message, onConfirm, onCancel) {
	// $(".modal-header").css({
	// 	"color": "#000",
	// 	"background-color": "#fff"
	// });
	$('#confirmModalTitle').text(title);
	$('#confirmModalBody').html(message);
	$('#confirmModal').modal('show');

	// Remove previous handlers
	$('#confirmYes').off('click');
	$('#confirmModal .btn-secondary').off('click');
	$('#confirmModal').off('hidden.bs.modal');

	// Track if user confirmed
	let confirmed = false;

	$('#confirmYes').on('click', function () {
		confirmed = true;
		$('#confirmModal').modal('hide');
		if (typeof onConfirm === 'function') {
			onConfirm();
		}
	});

	$('#confirmModal .btn-secondary').on('click', function () {
		confirmed = false;
		$('#confirmModal').modal('hide');
		if (typeof onCancel === 'function') {
			onCancel();
		}
	});

	$('#confirmModal').on('hidden.bs.modal', function () {
		if (!confirmed && typeof onCancel === 'function') {
			onCancel();
		}
	});
}


async function updateTecAndOptical(tecToTurnOn, dataUpdated, isShowMsg) {
	$(".loaderDiv").css("display", "block");

	let allowedTECs = [];
	let blockedTECs = [];

	for (let tec of tecToTurnOn) {
		let currentTemp = await new Promise(resolve => {
			$.ajax({
				type: "GET",
				url: "../cgi/cgi_TECManager.py",
				dataType: "json",
				data: { requestType: "get_current_temperature", id: tec.Id },
				success: (res) => res.status === "fail" ? resolve(-1) : resolve(parseFloat(res.getCurrent)),
				error: () => resolve(-1),
			});
		});

		if (currentTemp === -1) {
			blockedTECs.push(tec);
		} else {
			allowedTECs.push(tec);
		}
	}

	let finalAllowedTECs = [];
	for (let tec of allowedTECs) {
		let success = await new Promise(resolve => {
			$.ajax({
				type: "GET",
				url: "../cgi/cgi_TECManager.py",
				dataType: "json",
				data: {
					requestType: "update_TEC",
					id: tec.Id,
					name: tec.name,
					set_current: tec.setTemp,
					set_on_off_state: 1,
				},
				success: (res) => resolve(res.status !== "fail"),
				error: () => resolve(false),
			});
		});

		if (success) {
			console.log(`TEC ${tec.Id} turned ON`);
			finalAllowedTECs.push(tec);
		} else {
			blockedTECs.push(tec);
		}
	}

	if (blockedTECs.length > 0) {
		blockedTECs.forEach(tec => {
			let idx = dataUpdated.findIndex(d => d.id === tec.Id);
			if (idx !== -1) {
				dataUpdated[idx].set_current = 0;
				dataUpdated[idx].set_on_off_state = 0;
			}
		});

		showModal(
			"Error",
			`${blockedTECs.map(t => `TEC : ${t.Id}, Laser : ${t.Id} - 0 and Off`).join("<br>")}`
		);
	}

	for (let row of dataUpdated) {
		if (finalAllowedTECs.length > 0 && !finalAllowedTECs.find(t => t.Id === row.id)) {
			continue;
		}

		await new Promise(resolve => {
			$.ajax({
				type: "GET",
				url: "../cgi/cgi_IDriveManager.py",
				dataType: "json",
				data: {
					requestType: "update_i_drive",
					id: row.id,
					set_current: row.set_current,
					set_on_off_state: row.set_on_off_state
				},
				success: (response) => {
					if (isShowMsg) {
						if (response.status === "fail") {
							showModal("Error", response.description);
						} else {
							showModal("Success", response.description);
						}
					}
					resolve();
				},
				error: () => resolve(),
			});
		});
	}

	$(".loaderDiv").css("display", "none");

	if (dataUpdated.length > 0) {
		loadModuleControlData();
	}
}



function saveStateOpticalCombData(id, set_frequency_state, state) {
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_ModeMapManager.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "update_state_mode_map",
			id,
			set_on_off_state: state,
			set_power_state: set_frequency_state
		},
		success: function (response) {

		},
		error: function (ex) {
			$("#test").html(ex.responseText);
		}
	});
}


// for email form of connection page
function enableFormField() {
	$('#recipientEmail').prop("disabled", false);
}

$(document).ready(function () {



	/*-------------------------------Connection-------------------------------*/
	$('#myModal').on('hidden.bs.modal', function () {
		if (mymodal.find('.modal-title').text() == "Email Error") {
			$(".modal-header").css({
				"color": "#000",
				"background-color": "#fff"
			});
			$(".close").css({
				"color": "#000"
			});
			var setUpEmailModel = $("#setUpEmailModel");
			setUpEmailModel.modal('show');
		}
		// else if (showMsgBox == true) {
		// 	$(".msg-box").fadeIn();
		// 	setTimeout(function () {
		// 		$(".msg-box").fadeOut();
		// 	}, 2000);
		// 	showMsgBox = false;
		// }
	});
	/*-----------------------------Module Control-----------------------------*/



	function saveDemoStateOpticalCombData() {
		var demo_state = $("#demo-wavelength-turn-on-off").prop("checked") == true ? 1 : 0;
		// var set_on_off_state = $("#wavelength-turn-on-off").prop("checked") == true ? 1 : 0;
		$.ajax({
			type: "Get",
			url: "../cgi/cgi_CombMapManager.py",
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			data: {
				requestType: "update_demo_state_comb_map",
				id: opticalFrequencyCombData[0].id,
				// set_on_off_state: set_on_off_state,
				demo_state: demo_state
			},
			success: function (response) {
				if (opticalFrequencyCombData[0].demoState != demo_state) {
					if (demo_state == 1)
						ShowNotif("Central Wevelength On", 'success');
					else
						ShowNotif("Central Wevelength Off", 'success');
					loadDemoData();
				}

				//showModal('Success',response.description);
			},
			error: function (ex) {
				$("#test").html(ex.responseText);
			}
		});
	}


	//tooltip
	$(".tooltipBtn").mouseover(function () {
		var tooltiptext = $(this).children()[3];
		if ($($(this).children()[0]).prop("checked"))
			$(tooltiptext).text('Turn Off').fadeIn();
		else
			$(tooltiptext).text('Turn On').fadeIn();

	});
	$('.tooltipBtn').mouseleave(function () {
		var tooltiptext = $(this).children()[3];
		$(tooltiptext).fadeOut();
	});

	//warning box 
	$(".btn-cancel").click(function () {
		$(".error-msg").css("display", "none");
		$("#warning-password").val('');
		$(".warning-box-layout").fadeOut();
		$("body").css("overflow", "auto");
		$(".setvalue").prop("disabled", false);
		$(".setvalueidac").prop("disabled", false);
		$(".connectionSetValue").prop("disabled", false);
	});

	$("#warning-password").focus(function () {
		$(".error-msg").css("display", "none");
	});

	$(".btn-submit").click(function () {
		$.ajax({
			type: "Get",
			url: "../cgi/cgi_ValidateUser.py",
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			data: {
				requestType: "validate_password",
				password: $("#warning-password").val()
			},
			success: function (response) {
				if (parseInt(response.isvalidPassword) == 1) {
					if (commonOpticalCombId == "#demo-wavelength-turn-on-off") {
						isDemoSetUnprotectedMode = true;
						if (isIDriveValChange == true) {
							$("#demo-wavelength-switch-off").css("pointerEvents", "none");
						}
						else {
							$("#demo-wavelength-switch-off").css("pointerEvents", "auto");
						}
						$(".demo-setvalue").prop("disabled", false);
					} else {
						if (isIDriveValChange == true) {
							$("#currentController-switch-off").css("pointerEvents", "none");
						} else {
							$("#currentController-switch-off").css("pointerEvents", "auto");
						}
						isSetUnprotectedMode = true;
						$(".setvalue").prop("disabled", false);
						$(".setvalueidac").prop("disabled", false);
					}

					$(".warning-box-layout").fadeOut();
					$("body").css("overflow", "auto");
					$("#warning-password").val('');
					isSetUnprotectedMode = true;
					$(".connectionSetValue").prop("disabled", false);
				} else {
					$(".error-msg").css("display", "block");
				}
			},
			error: function (ex) {
				console.log(ex);
			}
		});
	});

	$(".setvalue").focus(function () {
		if (isSetUnprotectedMode == false) {
			commonOpticalCombId = "#wavelength-turn-on-off";
			if ($("#wavelength-turn-on-off").prop("checked") == true) {
				$(".state-box-layout").fadeIn();
			} else {
				$(this).prop("disabled", true);
				$(".warning-box-layout").fadeIn();
				$("#warning-password").focus();
			}
		}
	});

	$(".idriveBtn").click(function (e) {
		if (isSetUnprotectedMode == false) {
			commonOpticalCombId = "#wavelength-turn-on-off";
			e.preventDefault();
			if ($("#wavelength-turn-on-off").prop("checked") == true) {
				$(".state-box-layout").fadeIn();
			} else {
				$(".warning-box-layout").fadeIn();
				$("#warning-password").focus();
			}
		}
	});

	$(".close-icon").click(function () {
		$(".btn-cancel").trigger("click");
		$(".state-box-layout").fadeOut();
	});

	$(".set-on-yes").click(function () {
		$(commonOpticalCombId).prop("checked", false);
		isIDriveValChange = true
		saveStateOpticalCombData();
		$(".state-box-layout").hide();
		$(".warning-box-layout").fadeIn();
		$("#warning-password").focus();
	});

	$(".set-off-no").click(function () {
		$(".state-box-layout").fadeOut();
	});

	$("#wavelength-turn-on-off1,#frequency-turn-on-off1").change(function () {
		saveStateOpticalCombData();
	});
	$("#wavelength-turn-on-off2,#frequency-turn-on-off2").change(function () {
		saveStateOpticalCombData2();
	});
	$("#demo-wavelength-turn-on-off").change(function () {
		saveDemoStateOpticalCombData();
	});

	$(document).keypress(function (event) {
		var keycode = (event.keyCode ? event.keyCode : event.which);
		if (keycode == '13') {
			if ($(".state-box-layout").css('display') == 'block') {
				$(".set-on-yes").trigger('click');
			} else if ($(".warning-box-layout").css('display') == 'block') {
				$(".btn-submit").trigger('click');
			}
		} else if (keycode == '27') {
			if ($(".state-box-layout").css('display') == 'block') {
				$(".set-off-no").trigger('click');
			} else if ($(".warning-box-layout").css('display') == 'block') {
				$(".btn-submit").trigger('click');
			}
		}
	});

	// for validation of input boxes and sliders of connection, calibration, demo
	$(".connectionSetValue").focus(function (event) {
		if (isSetUnprotectedMode == false) {
			$(this).prop("disabled", true);
			$(".warning-box-layout").fadeIn();
			$("#warning-password").focus();
		}
	});

	/*------------------------------Demo Mode Page---------------------------------------------*/


	/*--------------------------- Calibration ----------------------------*/





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




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


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

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

	setInterval(readReverseSshStatus, 10000);


});

$("input[name='enReverseSSH']").on('change', function () {
	const selectedValue = $(this).val(); // use .val() instead of .attr('value')

	if (selectedValue === "no" && isReverseSSHConnected) {
		alert("Reverse SSH is already connected. Disconnect first before disabling.");

		// Re-select "yes"
		$("input[name='enReverseSSH'][value='yes']").prop("checked", true);
		return;
	}

	if (selectedValue === "yes") {
		$("#reverseSshConfig").show();
		$("#connectReverseSSH").attr("disabled", false).css("cursor", "pointer");
		$("#connectReverseSSH").show();
		$("#disconnectReverseSSH").show();
		$("#cancelReverseSSH").show();
	} else {
		$("#reverseSshConfig").hide();
		$("#connectReverseSSH").attr("disabled", true).css("cursor", "not-allowed");
		$("#connectReverseSSH").hide();
		$("#disconnectReverseSSH").hide();
		$("#cancelReverseSSH").hide();

	}
});


$("#rs_key_path").on("change", function () {
	const file = this.files[0];
	if (file) {
		$("#key_file_name").text(file.name);
	} else {
		$("#key_file_name").text("None");
	}
});
async function connectReverse() {
	let timer = 0;
	if (validateReverseSSHForm()) {
		if (!reverseSShData?.remote_ip) {
			await saveReverseSSHData();
			timer = 2000;
		}
		$('.loaderDiv').css('display', 'block');
		setTimeout(() => {

			$.ajax({
				type: "Get",
				url: "../cgi/cgi_EnableSsh.py",
				contentType: 'application/json',
				dataType: 'json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				data: {
					requestType: "connectReverseSSH",
				},
				success: function (response) {
					$('.loaderDiv').css('display', 'none');
					if (response?.status == "error") {
						$(".modal-header").css({
							"color": "#fff",
							"background-color": "#db4141"
						});
						$(".close").css({
							"color": "#fff"
						});
					}
					readReverseSshStatus();
					mymodal.find('.modal-title').text('Reverse SSH');
					mymodal.find('.modal-body').text(response.description).css({ "text-align": "center" });
					mymodal.modal('show');

					setTimeout(() => {
						mymodal.modal("hide")
						$(".modal-header").css({
							"color": "#000",
							"background-color": "#fff"
						});
						$(".close").css({
							"color": "#000"
						});
					}, autoClose)
				},
				error: function (ex) {
					$('.loaderDiv').css('display', 'none');
					console.log(ex);
				}
			});
		}, timer)
	}
}

function disconnectReverse() {
	$('.loaderDiv').css('display', 'block');
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_EnableSsh.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "disconnectReverseSSH",
		},
		success: function (response) {
			$('.loaderDiv').css('display', 'none');
			if (response?.status == "error") {
				$(".modal-header").css({
					"color": "#fff",
					"background-color": "#db4141"
				});
				$(".close").css({
					"color": "#fff"
				});
			}
			readReverseSshStatus();
			mymodal.find('.modal-title').text('Reverse SSH');
			mymodal.find('.modal-body').text(response.description).css({ "text-align": "center" });
			mymodal.modal('show');

			setTimeout(() => {
				mymodal.modal("hide")
				$(".modal-header").css({
					"color": "#000",
					"background-color": "#fff"
				});
				$(".close").css({
					"color": "#000"
				});
			}, autoClose)

		},
		error: function (ex) {
			$('.loaderDiv').css('display', 'none');
			console.log(ex);
		}
	});
}

function readReverseSshStatus() {
	let enable_reverse = $("input[name='enReverseSSH']:checked").val();
	if (enable_reverse == "no") {
		$("#connectReverseSSH").attr({ "disabled": true }).css("cursor", "not-allowed");
		$("#disconnectReverseSSH").attr("disabled", true).css("cursor", "not-allowed");
		$("#reverseSshStatus").text("");
		return
	}
	// else{
	// 	$("#connectReverseSSH").attr({"disabled": false}).css("cursor", "pointer");
	// 	$("#disconnectReverseSSH").attr({"disabled": false}).css("cursor", "pointer");
	// }
	if (!reverseSShData?.remote_ip) {
		return
	}
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_EnableSsh.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "reverseSSHStatus",
		},
		success: function (response) {
			isReverseSSHConnected = response?.connected;

			if (response?.connected) {
				$("#connectReverseSSH").attr({ "disabled": true }).css("cursor", "not-allowed");
				$("#disconnectReverseSSH").attr({ "disabled": false }).css("cursor", "pointer");
				$("#reverseSshStatus").text(response.description).css({ "color": "green" });
			}
			else {
				$("#connectReverseSSH").attr("disabled", false).css("cursor", "pointer");
				$("#disconnectReverseSSH").attr("disabled", true).css("cursor", "not-allowed");
				$("#reverseSshStatus").text(response.description).css({ "color": "red" });

			}

		},
		error: function (ex) {
			console.log(ex);
		}
	});
}


const cancelReverse = () => {
	let i = 0;
	if ($("#rs_remote_ip").val() && $("#rs_remote_ip").val() != reverseSShData?.remote_ip) {
		$("#rs_remote_ip").val(reverseSShData?.remote_ip),
			i++;
	}

	if ($("#rs_remote_port").val() && $("#rs_remote_port").val() != reverseSShData?.remote_port) {
		$("#rs_remote_port").val(reverseSShData?.remote_port),
			i++;
	}

	if ($("#rs_remote_user").val() && $("#rs_remote_user").val() != reverseSShData?.username) {
		$("#rs_remote_user").val(reverseSShData?.username),
			i++;
	}
	if (i > 0) {
		showModal("Alert!", "Changes Reverted!!");
	}
	else {
		showModal("Info!", "No Changes Detected!!");
	}
	// $("#rs_remote_ip").val(reverseSShData?.remote_ip),
	// $("#rs_remote_port").val(reverseSShData?.remote_port),
	// $("#rs_remote_user").val(reverseSShData?.username),
	$("#rs_local_port").val(reverseSShData?.local_port),
		$("#key_file_name").html(reverseSShData?.key_path).css({ "color": "green" })
	$("#rs_key_path").html(reverseSShData?.file_content);
	validateReverseSSHForm();
}

const checkboxes = [
	document.getElementById("ethernetCheckButton"),
	document.getElementById("serialCheckButton"),
	document.getElementById("remoteButton"),
	document.getElementById("sshButton"),
	document.getElementById("reverseSsh"),
	document.getElementById("remoteControlEnable"),
];

checkboxes.forEach(cb => {
	if (!cb) return;

	// Prevent unchecking via mouse
	cb.addEventListener("click", (e) => {
		e.preventDefault();
		cb.checked = true;
	});

	// Prevent unchecking via keyboard (space/enter)
	cb.addEventListener("keydown", (e) => {
		if (e.code === "Space" || e.key === " " || e.key === "Spacebar") {
			e.preventDefault();
			cb.checked = true;
		}
	});
});