<script lang="ts">
  import { getStores } from "$app/stores";

  import { sl3 } from "$lib/clients/sl3";
  import Modal from "$lib/components/common/Modal.svelte";
  import ModalBody from "$lib/components/common/ModalBody.svelte";
  import { getModalContext } from "$lib/components/contexts/ModalContext.svelte";
  import { getScopeContext } from "$lib/components/contexts/ScopeContext.svelte";
  import { getScopeListContext } from "$lib/components/contexts/ScopeListContext.svelte";
  import type { ScopeInput } from "$lib/models/scope";
  import type Scope from "$lib/models/scope";

  const {currentModal, closeModal} = getModalContext();
  const {updateScope} = getScopeContext();
  const {reloadScopeList} = getScopeListContext();
  const {page} = getStores();

  let scope: ScopeInput
  let scopeId: number
  
  let op: string
  let error: string
  let loading: boolean
  let show: boolean

  $: switch ($currentModal.name) {
    case "scope.create":
      initCreate()
      break;
    case "scope.edit":
      initEdit($currentModal.scope)
      break;

    default:
      loading = false;
      error = null;
      show = false;
  }

  function initCreate() {
    scope = {
      name: "",
      abbreviation: "",
      ownerName: "",
      customLabels: {},
    }

    op = "Create"
    show = true;
  }

  function initEdit(current: Scope) {
    scope = {
      name: current.name,
      abbreviation: current.abbreviation,
      ownerName: "",
      customLabels: current.customLabels,
    };
    scopeId = current.id;

    op = "Edit"
    show = true;
  }

  async function submit() {
    error = null;
    loading = true;

    try {
      switch (op) {
        case "Create":
          await sl3(fetch, $page.stuff.idToken).createScope(scope);
          await reloadScopeList();
          break;
        case "Edit":
          const res = await sl3(fetch, $page.stuff.idToken).updateScope(scopeId, scope);
          updateScope(res);
          break;
      }

      closeModal();
    } catch(err) {
      if (err.statusCode != null) {
        error = err.statusMessage;
      } else {
        error = err
      }
    } finally {
      loading = false;
    }
  }
</script>

<form on:submit|preventDefault={submit}>
  <Modal closable show={show} verb={op} noun="scope" disabled={loading} error={error}>
    <ModalBody>
      <label for="name">Name</label>
      <input name="name" type="text" bind:value={scope.name} />
      <label for="abbreviation">Abbreviation</label>
      <input name="abbreviation" type="text" bind:value={scope.abbreviation} />
      {#if op === "Create"}
        <label for="ownerName">Owner Name</label>
        <input name="ownerName" type="text" bind:value={scope.ownerName} />
      {/if}
    </ModalBody>
  </Modal>
</form>