<?php
// Name: Multi Scale Live View
session_start();
if(!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header("location: ../../../login.php"); exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Multi Scale Live View</title>
<style>
.message-container {
    border: 1px solid #ccc;
    padding: 10px;
    height: 80px;
	width: 400px;
    overflow-y: scroll;
    margin-bottom: 10px;
}
.weight-container {
    width: 400px;
    font-size: 2em;
    text-align: right;
}
.axles-container {
	text-align: right;
	td, th {
		width: 300px;
		border: 1px solid #333;
		padding-left: 20px;
		padding-right: 20px;
	}
}
.scaleLbl {
	text-align: left;
	font-size: 2em;
	display: flex;
	justify-content: space-between;
	color: #555
}
.scaleWt {
	font-size: 4em;
	margin-right: 10px;
}
.units {
	font-size: 2em;
}
.scaleStatus {
	color: blue;
}

.range {
	text-align: left;
	font-size: 2em;
	display: block;
	background-color: coral;
	color: white;
}

#connBtn {
	font-size: 5em;
}
</style>
</head>
<body>
<?php
$filename = "/mnt/tmpfs/liveview.txt";
if (file_exists($filename)) {
	$contents = file_get_contents($filename);
	$separator = chr(30);
	$items = explode($separator, $contents);
	if($items[0] != "Multi Scale") {
		echo '<h2>Currently running app is "' . $items[0] . '"</h2>';
		echo 'This page expects "Multi Scale" to be running';
	} else {
		echo '<h1>Multi Scale Live View</h1>';
	}
}
?>
<div class="axles-container" id="axlesDiv">___</div>
<div class="weight-container" id="wtDiv">
<table><tr><th>Axle</th><th>Weight</th><th> <th></tr>
</table>
</div> 
<!-- <button id="zeroBtn" onclick="zero()">Zero</button> -->
<button id="connBtn" onclick="window.location.reload();">Retry Connection</button>
<br><br><br><br><br>
<div class="message-container" id="messages"></div>

<!-- <input type="text" id="messageInput" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button> -->

<script type="text/javascript">
const output = document.getElementById("messages");
// Connect to the server on the same port and host as the HTTP page
const socket = new WebSocket('ws://' + window.location.host + ':8080/');

let connState = 0;
let lastDataCnt = 0;

function disconnected() {
	const wtdiv = document.getElementById("wtDiv");
	if(wtdiv) {
	    wtdiv.textContent = "Disconnected";
	}
	var zeroBtn = document.getElementById("zeroBtn");
	if(zeroBtn) {
		zeroBtn.style.display = "none";
	}
	var connBtn = document.getElementById("connBtn");
	if(connBtn) {
		connBtn.style.display = "block";
	}
	
	const container = document.getElementById("axlesDiv");
	container.textContent = "";

	connState = 0;
	logMessage("DISCONNECTED", "red");		
}

function connected() {
	logMessage("CONNECTED", "green");
	var zeroBtn = document.getElementById("zeroBtn");
	if(zeroBtn) {
		zeroBtn.style.display = "block";
	}
	var connBtn = document.getElementById("connBtn");
	if(connBtn) {
		connBtn.style.display = "none";
	}

	// Send an initial message to the server
	//socket.send("Hello from the client!");
	connState = 1;

}
// Wait until the DOM is fully loaded
window.addEventListener('load', function () {
    const timerDisplay = document.getElementById('timer');

    const timerId = setInterval(() => {
        lastDataCnt++;
		if(lastDataCnt == 10) {
			disconnected();
		}
    }, 500);
});

socket.onopen = function(event) {
	connected();
};

socket.onmessage = function(event) {
	try {
	    // Parse the JSON string into a JavaScript object
	    const data = JSON.parse(event.data);

	    // Validate that 'name' is a string
	    //if (typeof data.name !== 'string') {
	    //    throw new Error("'name' must be a string");
	    //}

	    // Validate that 'numbers' is an array of integers
	   // if (!Array.isArray(data.axles) || !data.axles.every(num => Number.isInteger(num))) {
	   //     throw new Error("'numbers' must be an array of integers");
	   // }

	   lastDataCnt = 0;
	   if(connState == 0) {
		connected();
	   }
	   
		//const wtdiv = document.getElementById("wtDiv");
		//if(wtdiv) {
		 //   wtdiv.textContent = data.wt;
		//}

	    // Access the parsed values
	    //console.log("wt:", data.wt);
		
		if(Array.isArray(data.wts)) {
		    //console.log("Axles:", data.axles);

			//const vehDone = data.vehDone;
	
			const container = document.getElementById("axlesDiv");
			    
			container.textContent = "";
			// Create the table element
			const table = document.createElement('table');
	
			    // Create table header
			 //   const headerRow = document.createElement('tr');
			    // Get headers from the keys of the first object
			    //const headers = Object.keys(dataArray[0]);
			//  const headers = [ "Scale", "Weight", " "];
			//  headers.forEach(headerText => {
			//        const th = document.createElement('th');
			//        th.textContent = headerText;
			//        headerRow.appendChild(th);
			//   });
			//   table.appendChild(headerRow);
	
			    // Create table rows and cells
			   let row = document.createElement('tr');
				let cnt = 1;
				let totCell = null;
			    data.wts.forEach(wt => {
					const td = document.createElement('td');

					let cellText = '<span class="scaleLbl"><span>';
					if(wt.num == 0) {
						cellText += 'Total';
					} else {
						cellText += 'Scale ';
						cellText += wt.num;
					}
					cellText += '</span><span class="scaleStatus">';
					if(wt.stat & 0x10) {
						cellText += "ER";
					} else if(wt.stat & 0x02) {
						cellText += "OC";
					} else if(wt.stat & 8) {
						cellText += "CZ";
					} else if(wt.stat & 4) {
						cellText += "BZ";
					} else if(wt.stat & 1) {
						cellText += "MO";
					}
					cellText += '</span><span>Gross</span></span><br>';
					cellText += '<span class="scaleWt">' + wt.gross + '</span><span class="units">' + wt.units + '</span></span>';
					if(wt.rnglbl != null) {
						cellText += '<span class="range" id="rng' + wt.num +'">' + wt.rnglbl + '</span>';
					}

					td.innerHTML = cellText;
					
					
					if(wt.num == 0) {
						totCell = td;
					} else {
						row.appendChild(td);
						if((cnt > 0) && (cnt % 4) == 0) {
							table.appendChild(row);
							row = document.createElement('tr');
						}
						cnt++;
					}
			    });
				if(totCell != null) {
					row.appendChild(totCell);
				}
				table.appendChild(row);

			    // Append the final table to the container div
			    container.appendChild(table);
		
						
				data.wts.forEach(wt => {
					const span = document.getElementById('rng' + wt.num);
					if(span != null) {
						if(wt.color != null) {
							span.style.color = wt.color;
						}
						if(wt.bkcolor != null) {
							span.style.backgroundColor = wt.bkcolor;
						}
					}
				});

			}
		//}

		// Call the function to create and display the table
		//createTable(data, 'table-container');
	    // Example: Sum the numbers
	   // const sum = data.numbers.reduce((acc, val) => acc + val, 0);
	    //console.log("Sum of numbers:", sum);

	} catch (error) {
	    // Handle invalid JSON or validation errors
	    console.error("Error parsing JSON:", error.message);
	}
};

socket.onclose = function(event) {
	disconnected();
};

socket.onerror = function(error) {
	const wtdiv = document.getElementById("wtDiv");
	if(wtdiv) {
	    wtdiv.textContent = "Error";
	}
    logMessage("ERROR: " + error.message, "red");
};

function sendMessage() {
    const input = document.getElementById("messageInput");
    const message = input.value;
    if (message) {
        socket.send(message);
        logMessage("SENT: " + message, "black");
        input.value = "";
    }
}

function logMessage(message, color) {
    const div = document.createElement("div");
    div.style.color = color;
    div.textContent = message;
    output.appendChild(div);
    // Auto-scroll to the latest message
    output.scrollTop = output.scrollHeight;
}

function zero() {
	socket.send("XZero");
	logMessage("SENT: Zero", "black");

}
</script>
</body>
</html>
