<?php
// Name: Highway Weigh Station 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>Highway Weigh Station 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;
}
.wts-container {
//	text-align: right;
	table-layout: fixed;
	min-width: 800px;
	
	font-size: 4em;
	//td {
	//	width: 200px;
	//}
	tr td:nth-child(1) {
		min-width: 200px;
		text-align: left;
	}
	tr td:nth-child(3) {
		//color: blue;
		//font-size: 24px;
		min-width: 40px;
	}
}
.tdWt {
	text-align: right;
	width: 500px;
}
.scaleLbl {
	text-align: left;
	font-size: 4vh;
	margin-right: 10px;
}
.scaleWt {
	font-size: 8vh;
	margin-right: 10px;
}
.units {
	font-size: 4vh;
}
.scaleStatus {
	color: blue;
	font-size: 4vh;
	margin-left: 10px;
}

#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] != "Highway Weigh Station") {
		echo '<h2>Currently running app is "' . $items[0] . '"</h2>';
		echo 'This page expects "Highway Weigh Station" to be running';
	} else {
		echo '<h1>Highway Weigh Station Live View</h1>';
	}
}
?>
<div class="wts-container">
<table>
<tr><td><span class="scaleLbl" id="lbl1"></span></td><td class="tdWt"><span><span class="scaleWt" id="wtval1"></span> <span class="units" id="units1"></span></span></td><td><span class="scaleStatus" id="status1"></span></td></tr>
<tr><td><span class="scaleLbl" id="lbl2"></span></td><td class="tdWt"><span><span class="scaleWt" id="wtval2"></span> <span class="units" id="units2"></span></span></td><td><span class="scaleStatus" id="status2"></span></td></tr>
<tr><td><span class="scaleLbl" id="lbl3"></span></td><td class="tdWt"><span><span class="scaleWt" id="wtval3"></span> <span class="units" id="units3"></span></span></td><td><span class="scaleStatus" id="status3"></span></td></tr>
<tr><td><span class="scaleLbl" id="lbl4"></span></td><td class="tdWt"><span><span class="scaleWt" id="wtval4"></span> <span class="units" id="units4"></span></span></td><td><span class="scaleStatus" id="status4"></span></td></tr>
<tr><td><span class="scaleLbl" id="lbl5"></span></td><td class="tdWt"><span><span class="scaleWt" id="wtval5"></span> <span class="units" id="units5"></span></span></td><td><span class="scaleStatus" id="status5"></span></td></tr>
</table>
</div>
<div class="weight-container" id="wtDiv">
</div> 
<button id="zeroBtn" onclick="zero()">Zero</button>
<button id="connBtn" onclick="window.location.reload();">Retry Connection</button>

<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 = "";
	for(let i = 1; i <= 5; i++) {
		const tdw = document.getElementById('wtval' + i);
		if(tdw != null) {
			tdw.textContent = "";
		}
		const tdu = document.getElementById('units' + i);
		if(tdu != null) {
			tdu.textContent = "";
		}
		const tds = document.getElementById('status' + i);
		if(tds != null) {
			tds.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 {
	    const data = JSON.parse(event.data);

	   lastDataCnt = 0;
	   if(connState == 0) {
		connected();
	   }
	   
		if(Array.isArray(data.wts)) {
	
				let cnt = 1;
				let totRow = null; 
				let lbl = "";
				let rowNum = 1;
			    data.wts.forEach(wt => {
					if(wt.num == 0) {
						rowNum = 5;
					} else {
						rowNum = wt.num;
					}
					
					const tdx = document.getElementById('lbl' + rowNum);
					if(tdx != null) {
						tdx.textContent = wt.lbl;
					}
					
					const tdw = document.getElementById('wtval' + rowNum);
					if(tdw != null) {
						tdw.textContent = wt.gross;
					}
					const tdu = document.getElementById('units' + rowNum);
					if(tdu != null) {
						tdu.textContent = wt.units;
					}
					const tds = document.getElementById('status' + rowNum);
					if(tds != null) {
						lbl = "";
						if(wt.stat & 0x10) {
							lbl = "ER";
						} else if(wt.stat & 0x02) {
							lbl = "OC";
						} else if(wt.stat & 8) {
							lbl = "CZ";
						} else if(wt.stat & 4) {
							lbl = "BZ";
						} else if(wt.stat & 1) {
							lbl = "MO";
						}
						tds.textContent = lbl;
					}

					cnt++;
			    });
				
		}

	} 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>
