<script lang="ts">
  import filesize from "filesize";
  import UpObject from "../components/display/UpObject.svelte";
  import Icon from "../components/utils/Icon.svelte";
  import Spinner from "../components/utils/Spinner.svelte";
  import api from "../lib/api";

  const stores = api.fetchStoreInfo();
</script>

<div class="store">
  <h1>Stores</h1>
  {#await stores}
    <Spinner />
  {:then stores}
    {#each Object.entries(stores) as [key, store] (key)}
      <h2>{key}</h2>
      <div class="totals">
        <strong>{store.totals.count}</strong> blobs,
        <strong>{filesize(store.totals.size)}</strong>
      </div>
      <table>
        <tr>
          <th>Hash</th>
          <th>Size</th>
          <th>Path</th>
          <th>Added</th>
          <th>Valid</th>
        </tr>
        {#each store.blobs as blob}
          <tbody>
            <tr class:invalid={!blob.paths[0].valid}>
              <td class="hash"
                ><UpObject link address={blob.hash} labels={[]} /></td
              >
              <td class="size">{filesize(blob.size)}</td>
              <td class="path">{blob.paths[0].path}</td>
              <td class="added">{blob.paths[0].added}</td>
              <td class="valid">
                {#if blob.paths[0].valid}
                  <Icon name="check" />
                {:else}
                  <Icon name="x" />
                {/if}
              </td>
            </tr>
            {#each blob.paths.slice(1) as path}
              <tr class:invalid={!path.valid}>
                <td />
                <td />
                <td class="path">{path.path}</td>
                <td class="added">{path.added}</td>
                <td class="valid">
                  {#if path.valid}
                    <Icon name="check" />
                  {:else}
                    <Icon name="x" />
                  {/if}
                </td>
              </tr>
            {/each}
          </tbody>
        {/each}
      </table>
    {/each}
  {:catch error}
    <div class="error">
      {error}
    </div>
  {/await}
</div>

<style lang="scss">
  .store {
    text-align: center;
  }

  .totals,
  th {
    font-size: larger;
  }

  table {
    border-spacing: 1em 0.25em;
    margin: 1em;
    text-align: initial;

    .size,
    .valid {
      text-align: center;
    }

    .size {
      white-space: nowrap;
    }

    .invalid {
      font-weight: 200;
    }

    tbody:nth-child(odd) {
      font-weight: 350;
    }

    tbody:nth-child(even) {
      font-weight: 450;
    }
  }
</style>
