<script lang="ts">
  import { sl3 } from "$lib/clients/sl3";
  import Modal from "$lib/components/common/Modal.svelte";
  import ModalBody from "$lib/components/common/ModalBody.svelte";
  import { getItemListContext } from "$lib/components/contexts/ItemListContext.svelte";
  import { getItemMultiListContext } from "$lib/components/contexts/ItemMultiListContext.svelte";
  import { getModalContext } from "$lib/components/contexts/ModalContext.svelte";
  import { getProjectContext } from "$lib/components/contexts/ProjectContext.svelte";
  import { getSprintListContext } from "$lib/components/contexts/SprintListContext.svelte";
  import ScheduledDateInput from "$lib/components/controls/ScheduledDateInput.svelte";
  import type Item from "$lib/models/item";

  const {currentModal, closeModal} = getModalContext();
  const {reloadProject} = getProjectContext();
  const {reloadItemList} = getItemListContext();
  const {reloadSprintList} = getSprintListContext();
  const {reloadItemLists} = getItemMultiListContext();

  let items: Item[]
  let openedDate: Date
  let scheduleDate: string;

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

  $: switch ($currentModal.name) {
    case "item.multischedule":
      init($currentModal.items)
      break;

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

  function init(selectedItems: Item[]) {
    openedDate = new Date();
    items = selectedItems.map(i => ({...i}));
    show = true;
    scheduleDate = selectedItems.find(i => i.scheduledDate)?.scheduledDate || "";
  }

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

    try {
      for (const item of items) {
        await sl3(fetch).updateItem(item.scopeId, item.id, {
          scheduledDate: scheduleDate || void(0),
          clearScheduledDate: scheduleDate === "",
        });
      }

      reloadItemLists();

      await reloadProject();
      await reloadItemList();
      await reloadSprintList();

      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="Schedule" noun="Items" disabled={loading} error={error}>
    <ModalBody>
      <label for="stats">Date</label>
      <ScheduledDateInput notScheduledText="Clear Scheduled Date" openDate={openedDate} bind:value={scheduleDate} />
      <p>This changes the scheduled date on all items in the requirement, regardless of whether they already have a scheduled date.</p>
    </ModalBody>
  </Modal>
</form>