<script>
  import { onMount } from 'svelte';
  import Icon from "$/client/components/Icon.svelte";
  import Layout from "$/admin/Layout.svelte";

  import api from "$/client/api.js";

  let tables = [];
  let show_all = false;
  let ignore = ["knex_migrations", "sqlite_sequence", "knex_migrations_lock"];

  onMount(async () => {
    let [status, data] = await api.get('/api/admin/schema');

    if(status === 200) {
      tables = data;
    } else {
      window.location = "/client/#/login";
    }
  });

</script>

<style>
  schemas {
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: auto;
    grid-column-gap: 1em;
  }

  schemas description table tr,
  schemas description table th {
    width: 100%;
  }

  schemas description h1 {
    margin-bottom: 0px;
  }

  buttons {
    display: flex;
    justify-content: space-between;
  }

  content {
    flex-direction: column;
    padding-right: 0.5rem;
    padding-left: 0.5rem;
    padding-top: 0.5rem;
    width: 100%;
  }
</style>

<content>
  <buttons>
    <span on:click={ () => show_all = !show_all }><Icon name={ show_all ? "eye-off" : "eye" } tooltip="Toggle internal tables." /><span>
  </buttons>
  <schemas>
    {#each tables as table, i}
      {#if show_all || !ignore.includes(table.name)}
        <description>
          <h1><a data-testid="table-name-{table.name}" href="/admin/#/table/{ table.name }/">{ table.name }</a></h1>

          <table>
            <thead>
              <tr><th>name</th><th>type</th><th>max</th><th>null</th><th>default</th>
            </thead>
            <tbody>
            {#each Object.keys(table._columns) as colname, i}
              <tr>
                <td>{colname}</td>
                <td>{table._columns[colname].type}</td>
                <td>{table._columns[colname].maxLength}</td>
                <td>{table._columns[colname].nullable}</td>
                <td>{table._columns[colname].defaultValue}</td>
              </tr>
            {/each}
            <tbody>
          </table>
        </description>
      {/if}
    {/each}
  </schemas>
</content>
