<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
  import Modal from "../components/Modal.svelte";
  import modalStore from "../stores/modal";
  import type { ItemResult } from "../models/item";
  import markStale from "../stores/markStale";

  export let deletion = false;
  export let creation = false;

  const md = $modalStore;
  let item: ItemResult = {
    id: "",
    groupId: "",
    groupWeight: 1,
    name: "",
    description: "",
    icon: "question",
    group: null,
  }
  let verb = "Add";
  if (md.name === "item.edit" || md.name === "item.delete") {
    item = md.item;
    verb = (md.name === "item.edit") ? "Edit" : "Delete";
  } else if (md.name === "item.add") {
    item.group = md.group;
  } else {
    throw new Error("Wrong form")
  }

  let name = item.name;
  let description = item.description;
  let groupWeight = item.groupWeight;
  let error = null;
  let loading = false;

  function onSubmit() {
    loading = true;

    if (creation) {
      stuffLogClient.createItem({
        groupId: item.group.id,
        name, description, groupWeight,
      }).then(() => {
        markStale("goal", "group");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else if (deletion) {
      stuffLogClient.deleteItem(item.id).then(() => {
        markStale("group");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else {
      stuffLogClient.updateItem(item.id, {
        name, description, groupWeight,
      }).then(() => {
        markStale("goal", "group", "project", "task");
        modalStore.close();
      }).finally(() => {
        loading = false;
      })
    }

    error = null;
  }

  function onClose() {
    modalStore.close();
  }
</script>

<Modal show title="{verb} Item" error={error} closable on:close={onClose}>
  <form on:submit|preventDefault={onSubmit}>
    <label for="groupName">Group</label>
    <input disabled name="groupName" type="text" value={item.group.name} />
    <label for="name">Name</label>
    <input disabled={deletion} name="name" type="text" bind:value={name} />
    <label for="description">Description</label>
    <textarea disabled={deletion} name="description" bind:value={description} />
    <label for="groupWeight">Group Weight</label>
    <input disabled={deletion} name="groupWeight" type="number" bind:value={groupWeight} />

    <hr />

    <button disabled={loading} type="submit">{verb} Item</button>
  </form>
</Modal>