<script lang="ts">
import { onMount } from "svelte";
import Chart from "util/Chart.svelte";
import { color_by_name } from "util/Util";
import { formatDataVolume, formatThousands } from "util/Formatting";
import { get_endpoint } from "lib/NovaAPI";

let { card_size = 1 }: {
	card_size?: number;
} = $props();

let chart_height = $derived((80 + (card_size * 60)) + "px")
let graph_downloads = $state(null)
let graph_egress = $state(null)

let load_graphs = async (minutes, interval) => {
	let end = new Date()
	let start = new Date()
	start.setMinutes(start.getMinutes() - minutes)

	try {
		let downloads_req = get_graph_data("downloads", start, end, interval);
		let egress_req = get_graph_data("egress", start, end, interval);
		let downloads = await downloads_req
		let egress = await egress_req

		graph_downloads.data().labels = downloads.timestamps;
		graph_downloads.data().datasets[0].data = downloads.amounts
		graph_egress.data().labels = egress.timestamps;
		graph_egress.data().datasets[0].data = egress.amounts

		graph_downloads.update()
		graph_egress.update()
	} catch (err) {
		console.error("Failed to update graphs", err)
		return
	}
}

let total_downloads = $state(0)
let total_egress = $state(0)

let get_graph_data = async (stat: string, start: Date, end: Date, interval: number) => {
	let resp = await fetch(
		get_endpoint() + "/user/time_series/" + stat +
		"?start=" + start.toISOString() +
		"&end=" + end.toISOString() +
		"&interval=" + interval
	)
	let resp_json: {
		timestamps: string[]
		amounts: number[]
	} = await resp.json()

	// Convert the timestamps to a human-friendly format
	resp_json.timestamps.forEach((val, idx) => {
		let date = new Date(val);
		let str: string = date.getFullYear().toString();
		str += "-" + ("00" + (date.getMonth() + 1)).slice(-2);
		str += "-" + ("00" + date.getDate()).slice(-2);
		str += " " + ("00" + date.getHours()).slice(-2);
		str += ":" + ("00" + date.getMinutes()).slice(-2);
		resp_json.timestamps[idx] = "  " + str + "  "; // Poor man's padding
	});

	// Add up the total amount and save it in the correct place
	let total = resp_json.amounts.reduce((acc, cur) => { return acc + cur }, 0)

	if (stat == "downloads") {
		total_downloads = total
	} else if (stat == "egress") {
		total_egress = total
	}

	return resp_json
}

let graph_timespan = $state(0)
let update_graphs = (minutes, interval) => {
	graph_timespan = minutes
	load_graphs(minutes, interval)
}

onMount(() => {
	graph_downloads.data().datasets = [
		{
			label: "Downloads",
			borderWidth: 2,
			pointRadius: 0,
			borderColor: color_by_name("highlight_color"),
			backgroundColor: color_by_name("highlight_color"),
		},
	];
	graph_egress.data().datasets = [
		{
			label: "Egress",
			borderWidth: 2,
			pointRadius: 0,
			borderColor: color_by_name("highlight_color"),
			backgroundColor: color_by_name("highlight_color"),
		},
	];

	update_graphs(43200, 1440);
})
</script>

<div class="time_buttons">
	<button
		onclick={() => update_graphs(1440, 1)}
		class:button_highlight={graph_timespan == 1440}
		class="group_first">
		Day
	</button>
	<button
		onclick={() => update_graphs(10080, 60)}
		class:button_highlight={graph_timespan == 10080}
		class="group_middle">
		Week
	</button>
	<button
		onclick={() => update_graphs(43200, 1440)}
		class:button_highlight={graph_timespan == 43200}
		class="group_middle">
		Month
	</button>
	<button
		onclick={() => update_graphs(131400, 1440)}
		class:button_highlight={graph_timespan == 131400}
		class="group_middle">
		Quarter
	</button>
	<button
		onclick={() => update_graphs(525600, 1440)}
		class:button_highlight={graph_timespan == 525600}
		class="group_middle">
		Year
	</button>
	<button
		onclick={() => update_graphs(1051200, 1440)}
		class:button_highlight={graph_timespan == 1051200}
		class="group_last">
		Two Years
	</button>
</div>

<Chart bind:this={graph_egress} data_type="bytes" height={chart_height} ticks={false}/>
<div class="center">
	{formatDataVolume(total_egress, 3)} egress used
</div>

<Chart bind:this={graph_downloads} data_type="number" height={chart_height} ticks={false}/>
<div class="center">
	{formatThousands(total_downloads)} downloads
</div>

<style>
.center {
	text-align: center;
}
.time_buttons {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	justify-content: center;
	gap: 2px;
}
.time_buttons > button {
	min-width: 3em;
	justify-content: center;
}
</style>
