<script lang="ts" context="module">
  let lastProjectId = "";
</script>

<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
  import Modal from "../components/Modal.svelte";
  import ProjectSelect from "../components/ProjectSelect.svelte";
  import TaskSelect from "../components/TaskSelect.svelte";
  import markStale from "../stores/markStale";
  import modalStore from "../stores/modal";

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

  const md = $modalStore;

  let projectId = "";
  let taskId = "";
  let groupId = "";
  let verb = "Add";

  if (md.name === "tasklink.delete") {
    projectId = md.project.id;
    taskId = md.task.id;
    groupId = md.project.groupId;
    verb = "Delete";
  } else if (md.name === "tasklink.add") {
    projectId = (md.project||{id:""}).id || lastProjectId;
    taskId = (md.task||{id:""}).id;
    groupId = md.project?.groupId;
  } else {
    throw new Error(`Wrong form ${md.name}`)
  }

  let error = null;
  let loading = false;

  function onSubmit() {
    loading = true;
    error = null;

    if (creation) {
      stuffLogClient.createTaskLink(projectId, taskId).then(() => {
        markStale("goal", "project");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
        lastProjectId = projectId;
      })
    } else if (deletion) {
      stuffLogClient.deleteTaskLink(projectId, taskId).then(() => {
        markStale("goal", "project");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
        lastProjectId = projectId;
      })
    }
  }
</script>

<Modal show title="{verb} Link" error={error} closable on:close={modalStore.close}>
  <form on:submit|preventDefault={onSubmit}>
    <label for="taskId">Source Task</label>
    <TaskSelect disabled={deletion} name="taskId" bind:value={taskId} />
    <label for="projectId">Destination Project</label>
    <ProjectSelect disabled={deletion} name="projectId" bind:value={projectId} groupId={groupId || ""} />

    <hr />

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