<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
  import Modal from "../components/Modal.svelte";
  import modalStore from "../stores/modal";
  import IconSelect from "../components/IconSelect.svelte";
  import { DEFAULT_ICON } from "../external/icons";
  import type { IconName } from "../external/icons";
  import type { GroupResult } from "../models/group";
  import markStale from "../stores/markStale";

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

  const md = $modalStore;
  let group: GroupResult = {
    id: "",
    name: "",
    description: "",
    icon: DEFAULT_ICON,
    items: [],
  };
  let verb = "Add";
  if (md.name === "group.edit" || md.name === "group.delete") {
    group = md.group;
    verb = (md.name === "group.edit") ? "Edit" : "Delete";
  } else if (md.name !== "group.add") {
    throw new Error("Wrong form")
  }

  let name = group.name;
  let description = group.description;
  let icon = group.icon as IconName;
  let error = null;
  let loading = false;

  function onSubmit() {
    loading = true;

    if (creation) {
      stuffLogClient.createGroup({
        name, description, icon,
      }).then(() => {
        markStale("group");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else if (deletion) {
      stuffLogClient.deleteGroup(group.id).then(() => {
        markStale("group");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else {
      stuffLogClient.updateGroup(group.id, {
        name, description, icon,
      }).then(() => {
        markStale("group", "goal", "project", "task");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    }

    error = null;
  }

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

<Modal show title="{verb} Group" error={error} closable on:close={onClose}>
  <form on:submit|preventDefault={onSubmit}>
    <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="icon">Icon</label>
    <IconSelect disabled={deletion} bind:value={icon} />

    <hr />

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