var g_deviceName = sessionStorage.getItem("configData");
var isTimeOutFunction = false;
var isTimeChartCalled = false;
var isGraphThere = false;

$(document).ready(function () {
	loadCurrentSettings();
	function getStat(name,status) {
		let stateImg = "";
    	let cssClass = "";
		if (status == 0 || status == null){
			stateImg = "../images/redLed.png";
			cssClass = "blink-red";
		}
		else if (status == 1)
			stateImg = "../images/greenLed.png";
		else{
			stateImg = "../images/warningLed.png";
			// cssClass = "blink-warning";
		}
		if (name == "TEC" || name == "Current Controller"){
			if (status == 0){
				stateImg = "../images/greenLed.png";
				cssClass = "blink-green";
			}
			else if (status == 2) {
				stateImg = "../images/warningLed.png";
				cssClass = ""
			}
			else if (status == 1) {
				stateImg = "../images/redLed.png";
				cssClass = "blink-red";
			}
		}
		return `<img class="led-space ${cssClass}" src="${stateImg}" />`;
	}

	function getStatDetails(name,status) {
		if (name == "TEC" || name == "Current Controller"){
			if (status == 0)
				return "Connected";       // Connected
			else if (status == 1)
				return "TEC Disc";   // TEC Disconnected
			else if (status == 2)
				return "Laser Disc"; // Laser Disconnected
		}
	}
	function loadCurrentSettings() {
		$.ajax({
			type: "Get",
			url: "../cgi/cgi_statusPageManager.py",
			contentType: 'application/json',
			dataType: 'json',
			headers: { 'Access-Control-Allow-Origin': '*' },
			data: { requestType: "read_currentSettingsAdoptionELS" },
			success: function (response) {
				$(".loaderDiv").hide();
				data = response;
				//current settings						
				$("#demultiplexDataValue1").append(' ' + data.Demultiplexer_Output_1);
				$("#demultiplexDataValue2").append(' ' + data.Demultiplexer_Output_2);
				$("#demultiplexDataValue3").append(' ' + data.Demultiplexer_Output_3);
				$("#demultiplexDataValue4").append(' ' + data.Demultiplexer_Output_4);
				// $("#featuresData1").append(' ' + (data["laser_data"][0] ?? 0));
				// $("#featuresData2").append(' ' + (data["laser_data"][1] ?? 0));
				// $("#featuresData3").append(' ' + (data["laser_data"][2] ?? 0));
				// $("#featuresData4").append(' ' + (data["laser_data"][3] ?? 0));
				$("#settingAppendDiv").empty();
				data?.current_controller?.forEach((item, index) => {
					let data = `<div class="" style="width: 223px;">
						<span id="featuresData1" class="label ng-binding">Laser${index + 1 } Current(mA) : ${[0,1,2,3,4,5,6,7,8].includes(index) ? "&nbsp;" : ""} <strong>${item?.wavelength}</strong></span>
					</div>`
					$("#settingAppendDiv").append(data);
				})

				//states
				$.each(data, function (key, value) {
					var stateImg = "";
					var name = "";
					var img = "";
					// if(value==0 || value==null)
					// 		stateImg="../images/redLed.png";
					// else if(value==1)
					// 	stateImg="../images/greenLed.png";
					// else
					// 	stateImg="../images/warningLed.png";
					var array = [];
					switch (key) {
						case "ethernet":
							name = "Ethernet Connection";
							img = "../images/Ethernet-Connection.png";
							// array = 
							break;
						case "remote":
							name = "Remote Connection";
							img = "../images/Remote-Connection.png";
							break;
						// case "Demux Output 1":
						// 	name="Demux Output 1";
						// 	img ="../images/Demux-Output.png";
						// 	break;
						// case "Demux Output 2":
						// 	name="Demux Output 2";
						// 	img ="../images/Demux-Output.png";
						// 	break;
						// case "Demux Output 3":
						// 	name="Demux Output 3";
						// 	img ="../images/Demux-Output.png";
						// 	break;
						// case "Demux Output 4":
						// 	name="Demux Output 4";
						// 	img ="../images/Demux-Output.png";
						// 	break;
						case "Slave":
							name = "Laser";
							img = "../images/Slave-Section.png";
							// array = 
							break;
						case "current_controller":
							name = "Current Controller";
							img = "../images/Slave-Section.png";
							// array = 
							break;
						case "VOA":
							name = "Variable Optical Attenuator";
							img = "../images/VOA-Section.png";
							break;
						case "Coupler":
							name = "Coupler";
							img = "../images/1_4-Coupler.png";
							break;
						case "Master":
							name = "Master Laser";
							img = "../images/Master-Section.png";
							break;
						case "tec":
							name = "TEC";
							img = "../images/TEC.png";
							// array = 
							break;
						case "Fan":
							name = "Fan";
							img = "../images/Fans.png";
							// array = 
							break;
						case "Master":
							name = "Master";
							img = "../images/TEC.png";
							break;
						case "RF Synthesizer":
							name = "RF Synthesizer";
							img = "../images/RF-Synth.png";
							break;
						case "Temperature":
							name = "Temperature";
							img = "../images/Temperature.png";
							// array = 
							break;
						case "PowerSupply":
							name = "Power Supply";
							img = "../images/Power-Supply.png";
							// array = 
							break;
						case "VOA":
							name = "VOA";
							img = "../images/VOA-Section.png";
							break;
						case "Date Modulation":
							name = "Date Modulation";
							img = "../images/Date-Modulation.png";
							break;
					}
					if (name != "") {
						var htmlContent = "";
        
						if (value.length > 8) {
							var collapseId = "collapse_" + key.replace(/\s+/g, "_");
							var arrowId = "arrow_" + key.replace(/\s+/g, "_");

							htmlContent = `
								<div class="status-icon-space">
									<div style="display: flex; cursor: pointer;" 
										onclick="toggleCollapse('${collapseId}', '${arrowId}')">
										<img src="${img}">
										<span class="led-space"></span>
										<label style="cursor: pointer;">${name}</label>
										<span id="${arrowId}" style="margin-left:auto;">&#x25BC;</span>
									</div>
									<div id="${collapseId}" style="display:none; margin-top:5px;">
										${value.map((item) => `
											<div style="display: flex; margin-left: 50px;">
												${getStat(name,item.status)}
												<span>${item.name} - ${getStatDetails(name,item.status)}</span> 
											</div>
										`).join('')}
									</div>
								</div>
							`;
						} else {
							htmlContent = `
								<div class="status-icon-space">
									<div style="display: flex;">
										<img src="${img}">
										<span class="led-space"></span>
										<label>${name}</label>
									</div>
									${value.map((item) => `
										<div style="display: flex; margin-left: 50px;">
											${getStat("",item.status)}
											<span>${item.name}</span> 
										</div>
									`).join('')}
								</div>
							`;
						}

						$("#ethernetAppendDiv").append(htmlContent);

						$("#ethernetAppendDivResponive").append(htmlContent);
					}
				});

			},
			error: function (ex) {
				$("#test").html(ex.responseText);
				$(".loaderDiv").hide();
			}
		});
	}
	let selectedMetric = "T";

	$('.clsChartType').change(function () {
		isTimeOutFunction = false;
		selectedMetric = $(this).val();
		console.log($(this).val(), "value");
		ShowChart();
	});

	function ShowChart() {
		var scale = $("input[name='chartSclae']:checked").val();
		InitializeChart(g_deviceName, selectedMetric, scale);
	}
	$('.clsChartScale').change(function () {
		isTimeOutFunction = false;
		ShowChart();
	});

});
var mymodal = $('#myModal');
$("#switch_output").change((e) => {
	const checkbox = document.getElementById('myCheckbox');
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_statusPageManager.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: { 'Access-Control-Allow-Origin': '*' },
		data: { requestType: "output" },
		success: (response) => {
			mymodal.find('.modal-title').text('Turn All Outputs OFF');
			mymodal.find('.modal-body').text(response.message);
			mymodal.modal('show');
			setTimeout(() => {
				mymodal.modal("hide")
			}, autoClose)
		}
	})
})
$("#switch_module").change((e) => {
	const checkbox = document.getElementById('myCheckbox');
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_statusPageManager.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: { 'Access-Control-Allow-Origin': '*' },
		data: { requestType: "module" },
		success: (response) => {
			mymodal.find('.modal-title').text('Turn Module OFF');
			mymodal.find('.modal-body').text(response.message);
			mymodal.modal('show');
			setTimeout(() => {
				mymodal.modal("hide")
			}, autoClose)
		}
	})
})

function toggleCollapse(contentId, arrowId) {
    $("#" + contentId).toggle();
    var arrow = $("#" + arrowId);
    if ($("#" + contentId).is(":visible")) {
        arrow.html("&#x25B2;"); // ▲ up arrow
    } else {
        arrow.html("&#x25BC;"); // ▼ down arrow
    }
}