<?php
// Name: Batcher 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>DFC / Batcher Live View</title>
<style>
.message-container {
    border: 1px solid #ccc;
    padding: 10px;
    height: 200px;
    overflow-y: scroll;
    margin-bottom: 10px;
}
.weight-container {
    width: 400px;
    font-size: 2em;
    text-align: right;
}
.axles-container {
	text-align: right;
	font-size: 4em;
	tr td:LAST-CHILD {
		color: blue;
		font-size: 24px;
	}
}
#connBtn {
	font-size: 5em;
}
</style>
</head>
<body>
<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>

<div class="message-container" id="messages"></div>

<script type="text/javascript">
class ReconnectingWebSocket {
	constructor(url, protocols = [], options = {}) {
		this.url = url;
		this.protocols = protocols;
		this.options = Object.assign({
			reconnectInterval: 2000,   // Initial delay (ms)
		maxReconnectInterval: 240000, // Max delay (ms)
		reconnectDecay: 3,       // Delay growth factor
		maxRetries: Infinity,      // Retry forever by default
		debug: false
		}, options);

		this.retries = 0;
		this.forcedClose = false;
		this.connect();
	}

	connect() {
		if (this.options.debug) console.log("Connecting to", this.url);

		try {
			this.ws = new WebSocket(this.url, this.protocols);
		} catch (err) {
			console.error("WebSocket creation failed:", err);
			this.scheduleReconnect();
			return;
		}

		this.ws.onopen = (event) => {
			if (this.options.debug) console.log("Connected");
			this.retries = 0;
			if (this.onopen) this.onopen(event);
		};

			this.ws.onmessage = (event) => {
				if (this.onmessage) this.onmessage(event);
			};

				this.ws.onerror = (event) => {
					if (this.options.debug) console.error("WebSocket error:", event);
					if (this.onerror) this.onerror(event);
				};

					this.ws.onclose = (event) => {
						if (this.forcedClose) {
							if (this.options.debug) console.log("Connection closed by client");
							return;
						}
						if (this.options.debug) console.warn("Connection lost:", event.reason);
						this.scheduleReconnect();
						if (this.onclose) this.onclose(event);
					};
	}

	scheduleReconnect() {
		if (this.retries >= this.options.maxRetries) {
			if (this.options.debug) console.error("Max retries reached. Giving up.");
			if (this.onreconnecting) this.onreconnecting("Max retries reached. Giving up.");
			return;
		}
		const delay = Math.min(
			this.options.reconnectInterval * Math.pow(this.options.reconnectDecay, this.retries),
							   this.options.maxReconnectInterval
		);
		this.retries++;
		if (this.options.debug) console.log(`Reconnecting in ${delay}ms...`);
		if (this.onreconnecting) {
			const secs = delay / 1000;
			this.onreconnecting(`Reconnecting in ${secs} seconds...`);
		}
		setTimeout(() => this.connect(), delay);
	}

	send(data) {
		if (this.ws && this.ws.readyState === WebSocket.OPEN) {
			this.ws.send(data);
		} else {
			console.warn("Cannot send message: WebSocket not open");
		}
	}

	close() {
		this.forcedClose = true;
		if (this.ws) this.ws.close();
	}
}

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/');
const socket = new ReconnectingWebSocket('ws://' + window.location.host + ':8080/', [], { debug: true });

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() {
	const wtdiv = document.getElementById("wtDiv");
	if(wtdiv) {
	    wtdiv.textContent = "";
	}
	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.onreconnecting = function(msg) {
	logMessage(msg, "black");
}

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 cnt = 1;
			    data.wts.forEach(wt => {
			        const row = document.createElement('tr');
					const td = document.createElement('td');
					td.textContent = wt.num;
					row.appendChild(td);
		            const td2 = document.createElement('td');
			        td2.textContent = wt.wt;
					row.appendChild(td2);
					
					const td3 = document.createElement('td');
					td3.textContent = "";
		            row.appendChild(td3);
			        table.appendChild(row);
					cnt++;
			    });
	
			    // Append the final table to the container div
			    container.appendChild(table);
			}
		//}

		// 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 getLocalDateTimeString() {
	const now = new Date();

	// Helper to pad single digits with leading zero
	const pad = (num) => String(num).padStart(2, '0');

	const year = now.getFullYear();
	const month = pad(now.getMonth() + 1); // Months are zero-based
	const day = pad(now.getDate());

	const hours = pad(now.getHours());
	const minutes = pad(now.getMinutes());
	const seconds = pad(now.getSeconds());

	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function logMessage(message, color) {
    const div = document.createElement("div");
    div.style.color = color;
    div.textContent = getLocalDateTimeString() + " " + 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>
