<script lang="ts">
import { get_endpoint, get_user, type User } from "lib/NovaAPI";
import { onMount } from "svelte";
import HotlinkProgressBar from "user_home/HotlinkProgressBar.svelte";
import StorageProgressBar from "user_home/StorageProgressBar.svelte";
import { formatThousands } from "util/Formatting";

let transfer_cap = $state(0)
let transfer_used = $state(0)
let storage_limit = $state(0)

let load_direct_bw = () => {
	let today = new Date()
	let start = new Date()
	start.setDate(start.getDate() - 30)

	fetch(
		get_endpoint() + "/user/time_series/egress" +
		"?start=" + start.toISOString() +
		"&end=" + today.toISOString() +
		"&interval=60"
	).then(resp => {
		if (!resp.ok) { return Promise.reject("Error: " + resp.status); }
		return resp.json();
	}).then(resp => {
		let total = resp.amounts.reduce((accum, val) => accum += val, 0);
		transfer_used = total
	}).catch(e => {
		console.error("Error requesting time series: " + e);
	})
}

let user: User = $state()
onMount(async () => {
	user = await get_user()

	if (user.monthly_transfer_cap > 0) {
		transfer_cap = user.monthly_transfer_cap
	} else if (user.subscription.monthly_transfer_cap > 0) {
		transfer_cap = user.subscription.monthly_transfer_cap
	} else {
		transfer_cap = -1
	}

	storage_limit = user.subscription.storage_space

	load_direct_bw()
})

</script>

{#if user !== undefined}
	Storage space used:
	<StorageProgressBar used={user.storage_space_used} total={storage_limit}/>
	<br/>

	File count: {formatThousands(user.filesystem_node_count)}
	<br/><br/>

	Egress used (30 days):
	(<a href="/user/sharing/bandwidth">set custom limit</a>)
	<HotlinkProgressBar used={transfer_used} total={transfer_cap}></HotlinkProgressBar>
{/if}
