<script>
  import { link } from 'svelte-spa-router';
  import Icon from "$/client/components/Icon.svelte";
  import Spinner from "$/client/components/Spinner.svelte";
  import Layout from "$/admin/Layout.svelte";
  import api from "$/client/api.js";
  import DataTable from "$/client/components/DataTable.svelte";
  import { defer } from "$/client/helpers.js";
  import { onMount } from "svelte";

  let rows = [];
  let column_names = [];
  let pagination =  { currentPage: 1 }
  const load_promise = defer("datatable load promise");

  export let params = {};

  // BUG: this works around stupid in DataTable where
  // paginating causes the link to id be invalid
  const link_url = r => `/admin/#/table/${params.table}/${r.id}/`;

  const update_data = async (url, options) => {
    const { currentPage } = pagination;
    options.currentPage = currentPage;

    let [status, results] = await api.get(url, options);

    if(status == 200) {
      // generates the _url used by the DataTabe component
      rows = results.data.map(r => {
        r._url = link_url(r);
        return r;
      });

      pagination = Object.assign(pagination, results.pagination);

      if(rows.length > 0) {
        column_names = Object.keys(rows[0]);
      }

      load_promise.resolve();
    } else {
      window.location = "/client/#/login";
    }
  }

  const full_query = async () => {
    await update_data('/api/admin/table', {name: params.table});
  }

  const search_query = async (event) => {
    let search_text = event.detail;
    await update_data('/api/admin/table', {name: params.table, search: search_text});
  }

  const clear_search = async () => {
    await update_data('/api/admin/table', {name: params.table});
  }

  const cell_click = () => {
    // I was going to the record when you click but that prevents people from
    // copy-pasting the data.  I think I'll leave it alone.
  }

  onMount(async () => {
    await full_query();
  });
</script>

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


<Layout fullwidth={ true } authenticated={ true } testid="page-admin-table">
  <content>
    <h1><a href="/" use:link><Icon name="arrow-left-circle" size="36"/></a> { params.table } Table</h1>
    {#await load_promise}
      <Spinner />
    {:then}
      <DataTable rows={ rows }
                 columns={ column_names }
                 bind:pagination
                 on:full_query={ full_query }
                 on:search_query={ search_query }
                 on:clear_search={ clear_search }
                 on:cell_click={ cell_click }>

            <a data-testid="link-create" href="/table/create/{params.table}/" use:link><Icon name="file-plus" size="36" tooltip="Create." /></a>
      </DataTable>
    {/await}
  </content>
</Layout>
