<script>
  import Island from '$lib/islands/island.svelte';
  import Header from '$lib/navigation/header.svelte';
  import Loading from '$lib/navigation/loading.svelte';
  import Nav from '$lib/navigation/nav.svelte';
  const title = 'Statistics';

  async function getData() {
    const url = 'https://owlboard.info/misc/server/stats';
    const res = await fetch(url);
    return await res.json();
  }

  function U2L(input) {
    try {
      const datetime = new Date(input * 1000);
      return datetime.toLocaleString();
    } catch (err) {
      console.log(err);
      return false;
    }
  }
</script>

<Header {title} />

{#await getData()}
  <Loading />
{:then data}
  <br />
  <p>API Server:<br /><span>{data?.hostname}</span></p>
  <p>Runtime Mode: <span>{data?.runtimeMode}</span></p>
  <p>Stats Reset: <span>{U2L(data?.reset) || 'Unknown'}</span></p>
  <h2>Last Update</h2>
  <p>Timetable: <span>{U2L(data?.updateTimes?.timetable)}</span></p>
  <p>Location Ref: <span>{U2L(data?.updateTimes?.corpus)}</span></p>
  <p>PIS Codes: <span>{U2L(data?.updateTimes?.pis)}</span></p>
  <p>Reason Codes: <span>{U2L(data?.updateTimes?.reasonCodes)}</span></p>

  <h2>Request Counts</h2>
  <p>LDBWS API: <span>{data?.requestCounts?.ldbws_api}</span></p>
  <p>LDBSVWS API: <span>{data?.requestCounts?.lsbsvws_api}</span></p>
  <p>Location Reference API: <span>{data?.requestCounts?.corpus_api}</span></p>
  <p>Timetable: <span>{data?.requestCounts?.timetable_db}</span></p>
  <p>PIS: <span>{data?.requestCounts?.pis_db}</span></p>
  <p>Location Reference: <span>{data?.requestCounts?.corpus_db}</span></p>
  <p>Stations: <span>{data?.requestCounts?.stations_db}</span></p>

  <h2>Database Lengths</h2>
  <p>Users: <span>{data?.dbLengths?.users}</span></p>
  <p>Pending Registrations: <span>{data?.dbLengths?.registrations}</span></p>
  <p>CORPUS: <span>{data?.dbLengths?.corpus}</span></p>
  <p>Stations: <span>{data?.dbLengths?.stations}</span></p>
  <p>PIS: <span>{data?.dbLengths?.pis}</span></p>
  <p>Timetable: <span>{data?.dbLengths?.timetable}</span></p>
  <p>Reason Codes: <span>{data?.dbLengths?.reasonCodes}</span></p>
{:catch}
  <Island>
    <p style="font-weight:600">Unable to connect to server</p>
  </Island>
{/await}

<Nav />

<style>
  span {
    color: white;
  }
  p {
    margin: 0;
    color: lightgray;
  }
  h2 {
    font-family: urwgothic, sans-serif;
    margin-bottom: 2px;
    margin-top: 8px;
  }
</style>
