<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
  import Checkbox from "../components/Checkbox.svelte";
import ItemSelect from "../components/ItemSelect.svelte";
  import Modal from "../components/Modal.svelte";
  import type { LogResult } from "../models/log";
  import markStale from "../stores/markStale";
  import modalStore from "../stores/modal";
  import { formatFormTime } from "../utils/time";

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

  const md = $modalStore;
  let log: LogResult = {
    id: "",
    taskId: "",
    itemId: "",
    loggedTime: new Date().toISOString(),
    description: "",
    itemAmount: 1,
    secondaryItemAmount: 0,
    secondaryItemId: null,
    task: null,
    item: null,
    secondaryItem: null,
  }
  let defaultMarkInactive = false;
  let verb = "Add";
  if (md.name === "log.edit" || md.name === "log.delete") {
    log = md.log;
    verb = (md.name === "log.edit") ? "Edit" : "Delete";
  } else if (md.name === "log.add") {
    defaultMarkInactive = md.task.completedAmount >= (md.task.itemAmount - 1);
    log.task = md.task;
  } else {
    throw new Error("Wrong form")
  }

  let loggedTime = formatFormTime(log.loggedTime);
  let description = log.description;
  let itemAmount = log.itemAmount;
  let secondaryItemId = log.secondaryItemId || "";
  let secondaryItemAmount = log.secondaryItemAmount;
  let markInactive = defaultMarkInactive;
  let error = null;
  let loading = false;

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

    if (creation) {
      stuffLogClient.createLog({
        taskId: log.task.id, 
        loggedTime: new Date(loggedTime).toISOString(),
        secondaryItemId: secondaryItemId || null,
        description, itemAmount, secondaryItemAmount,
      }).then(() => {
        markStale("project", "task", "goal", "log");

        if (markInactive) {
          return stuffLogClient.updateTask(log.task.id, {active: false, statusTag: "completed"});
        }
      }).then(() => {
        markStale("project", "task");

        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else if (deletion) {
      stuffLogClient.deleteLog(log.id).then(() => {
        markStale("project", "task", "goal", "log");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else {
      stuffLogClient.updateLog(log.id, { 
        loggedTime: new Date(loggedTime).toISOString(),
        secondaryItemId: secondaryItemId || null,
        clearSecondaryItemId: !secondaryItemId,
        description, itemAmount, secondaryItemAmount
      }).then(() => {
        markStale("project", "task", "goal", "log");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    }
  }

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

<Modal show title="{verb} Log" error={error} closable on:close={onClose}>
  <form on:submit|preventDefault={onSubmit}>
    <label for="taskName">Task</label>
    <input disabled name="taskName" type="text" value={log.task.name} />
    <label for="loggedTime">Logged Time</label>
    <input disabled={deletion} name="loggedTime" type="datetime-local" bind:value={loggedTime} />
    <label for="itemAmount">Item Amount</label>
    <input disabled={deletion} name="itemAmount" type="number" bind:value={itemAmount} />
    <label for="description">Description</label>
    <textarea disabled={deletion} name="description" bind:value={description} />
    <label for="secondaryItemId">Secondary Item</label>
    <ItemSelect name="secondaryItemId" disabled={deletion} optional bind:value={secondaryItemId} />
    {#if secondaryItemId != ""}
      <label for="secondaryItemAmount">Secondary Item Amount</label>
      <input disabled={deletion} name="secondaryItemAmount" type="number" bind:value={secondaryItemAmount} />
    {/if}

    <Checkbox disabled={!creation} bind:checked={markInactive} label="Mark task inactive/completed." />

    <hr />

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