<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 Checkbox from "$lib/components/layout/Checkbox.svelte";
  import type { Requirement } from "$lib/models/project";
  import type Scope from "$lib/models/scope";
  import type { StatInput } from "$lib/models/stat";
  import type Stat from "$lib/models/stat";

  const {currentModal, closeModal} = getModalContext();
  const {scope, upsertStat} = getScopeContext();
  const {page} = getStores();

  let stat: StatInput
  let statId: number
  let op: string

  let error: string
  let loading: boolean
  let show: boolean

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

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

  function initCreate(scope: Scope, requirement?: Requirement) {
    let stats = requirement?.stats.map(s => ({statId: s.id, required: 0, acquired: 0}));
    if (stats == null) {
      stats = scope.stats.map(s => ({statId: s.id, required: 0, acquired: 0}))
    }

    stat = {
      name: "",
      weight: 1,
      primary: false,
      description: "",
      allowedAmounts: null,
    }

    op = "Create"
    show = true;
  }

  function initEdit(current: Stat) {
    stat = {
      name: current.name,
      weight: current.weight,
      primary: current.primary,
      description: current.description,
      allowedAmounts: current.allowedAmounts ? current.allowedAmounts.slice() : void(0),
    };
    statId = current.id;
 
    op = "Edit"
    show = true;
  }

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

    try {
      switch (op) {
        case "Create":
          const createdStat = await sl3(fetch, $page.stuff.idToken).createStat($scope.id, stat);
          upsertStat(createdStat);
          break;
        case "Edit":
          const editedStat = await sl3(fetch, $page.stuff.idToken).updateStat($scope.id, statId, {
            ...stat,
            allowedAmounts: void(0),
          });
          upsertStat(editedStat);
          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="Stat" disabled={loading} error={error}>
    <ModalBody>
      <label for="name">Name</label>
      <input name="name" type="text" bind:value={stat.name} />
      <label for="weight">Weight</label>
      <input name="weight" type="number" min={0} step={0.001} bind:value={stat.weight} />
      <label for="description">Description</label>
      <textarea name="description" bind:value={stat.description} />
      <Checkbox bind:checked={stat.primary} label="Primary" />
    </ModalBody>
  </Modal>
</form>