1/*
2 * Copyright (c) 2024, Witekio
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6async function fetchUptime()
7{
8	try {
9		const response = await fetch("/uptime");
10		if (!response.ok) {
11			throw new Error(`Response status: ${response.status}`);
12		}
13
14		const json = await response.json();
15		const uptime = document.getElementById("uptime");
16		uptime.innerHTML = "Uptime: " + json + " milliseconds"
17	} catch (error) {
18		console.error(error.message);
19	}
20}
21
22async function postLed(state)
23{
24	try {
25		const payload = JSON.stringify({"led_num" : 0, "led_state" : state});
26
27		const response = await fetch("/led", {method : "POST", body : payload});
28		if (!response.ok) {
29			throw new Error(`Response satus: ${response.status}`);
30		}
31	} catch (error) {
32		console.error(error.message);
33	}
34}
35
36function setNetStat(json_data, stat_name)
37{
38	document.getElementById(stat_name).innerHTML = json_data[stat_name];
39}
40
41window.addEventListener("DOMContentLoaded", (ev) => {
42	/* Fetch the uptime once per second */
43	setInterval(fetchUptime, 1000);
44
45	/* POST to the LED endpoint when the buttons are pressed */
46	const led_on_btn = document.getElementById("led_on");
47	led_on_btn.addEventListener("click", (event) => {
48		console.log("led_on clicked");
49		postLed(true);
50	})
51
52	const led_off_btn = document.getElementById("led_off");
53	led_off_btn.addEventListener("click", (event) => {
54		console.log("led_off clicked");
55		postLed(false);
56	})
57
58	/* Setup websocket for handling network stats */
59	const ws = new WebSocket("/");
60
61	ws.onmessage = (event) => {
62		const data = JSON.parse(event.data);
63		setNetStat(data, "bytes_recv");
64		setNetStat(data, "bytes_sent");
65		setNetStat(data, "ipv6_pkt_recv");
66		setNetStat(data, "ipv6_pkt_sent");
67		setNetStat(data, "ipv4_pkt_recv");
68		setNetStat(data, "ipv4_pkt_sent");
69		setNetStat(data, "tcp_bytes_recv");
70		setNetStat(data, "tcp_bytes_sent");
71	}
72})
73