<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
import Checkbox from "../components/Checkbox.svelte";
  import Modal from "../components/Modal.svelte";
  import goalStore, { fpGoalStore } from "../stores/goal";
import logStore from "../stores/logs";
  import modalStore from "../stores/modal";
  import projectStore, { fpProjectStore } from "../stores/project";
  import { formatFormTime } from "../utils/time";

  const md = $modalStore;
  if (md.name !== "log.add") {
    throw new Error("Wrong form");
  }
  const task = md.task;

  let loggedTime = formatFormTime(new Date);
  let description = "";
  let markInactive = task.completedAmount >= (task.itemAmount - 1);
  let error = null;
  let loading = false;

  function onSubmit() {
    loading = true;

    stuffLogClient.createLog({
      taskId: task.id, 
      loggedTime: new Date(loggedTime).toISOString(),
      description,
    }).then(() => {
      if (markInactive) {
        return stuffLogClient.updateTask(task.id, {active: false})
      }
    }).then(() => {
      modalStore.close();
    }).finally(() => {
      projectStore.markStale();
      fpProjectStore.markStale();
      goalStore.markStale();
      fpGoalStore.markStale();
      logStore.markStale();
    }).finally(() => {
      loading = false;
    })

    error = null;
  }

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

<Modal show title="Add Log" error={error} closable on:close={onClose}>
  <form on:submit|preventDefault={onSubmit}>
    <label for="taskName">Task</label>
    <input disabled name="taskName" type="text" bind:value={task.name} />

    <label for="loggedTime">Logged Time</label>
    <input name="loggedTime" type="datetime-local" bind:value={loggedTime} />
    <label for="description">Description</label>
    <textarea name="description" bind:value={description} />
    <Checkbox bind:checked={markInactive} label="Mark task inactive/completed." />

    <hr />

    <button disabled={loading} type="submit">Add Log</button>
  </form>
</Modal>