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

  export let params = {};

  let data = {};
  let error = "";
  let schema = {};
  const load_promise = defer();

  onMount(async () => {
    schema = await api.schema(params.table);

    if(schema === undefined) {
      error = "Failed to load schema.";
      load_promise.reject();
    } else {
      load_promise.resolve();
    }
  });

  const create_record = async () => {
    let [status, row] = await api.put(`/api/admin/table?name=${params.table}`, data);

    if(status == 200) {
      error = "";
      push(`/table/${params.table}/${row.id}/`);
    } else if(status == 401) {
      window.location = "/client/#/login";
    } else {
      error = "Failed saving record.";
      data = row;
    }
  }
</script>

<Layout authenticated={ true } testid="admin-create-page">
  {#await load_promise}
    ... loading ...
  {:then}
    <Form data={data} table={params.table} schema={ schema }>
      <a data-testid="button-back" href="/table/{ params.table }" use:link>
        <Icon name="arrow-left-circle" tooltip="Back to table." size="48" />
      </a>

      <span data-testid="button-create" on:click={ create_record }>
        <Icon name="save" tooltip="Create." size="48" />
      </span>
    </Form>
  {/await}

  {#if error}
    <toast-list class="bottom right active">
      <toast transition:fade|local>
        <error>{error}</error>
      </toast>
    </toast-list>
  {/if}
</Layout>
