<script lang="ts">
  import stuffLogClient from "../clients/stufflog";
import DeadlineSelect from "../components/DeadlineSelect.svelte";
  import ItemSelect from "../components/ItemSelect.svelte";
  import Modal from "../components/Modal.svelte";
import ProjectSelect from "../components/ProjectSelect.svelte";
  import StatusTagSelect from "../components/StatusTagSelect.svelte";
  import { iconNames } from "../external/icons";
  import type { TaskResult } from "../models/task";
  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 task: TaskResult = {
    id: "",
    itemId: "",
    projectId: "",
    itemAmount: 1,
    name: "",
    description: "",
    icon: iconNames[0],
    active: false,
    createdTime: "",
    item: null,
    logs: [],
    completedAmount: 0,
    statusTag: "to do",
  }
  let verb = "Add";
  if (md.name === "task.edit" || md.name === "task.delete") {
    task = md.task;
    verb = (md.name === "task.edit") ? "Edit" : "Delete";
  } else if (md.name === "task.add") {
    task.projectId = md.project.id;
    task.project = md.project;

    if (md.project.tasks.length > 0) {
      task.itemId = md.project.tasks[0].itemId;
    }
  } else {
    throw new Error("Wrong form")
  }

  let endTime = formatFormTime(task.endTime);
  let itemId = task.itemId;
  let name = task.name;
  let description = task.description;
  let itemAmount = task.itemAmount;
  let statusTag = task.statusTag || "";
  let projectId = task.projectId;
  
  let error = null;
  let loading = false;

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

    if (creation) {
      stuffLogClient.createTask({
        projectId: task.projectId, 
        itemId: itemId,
        active: statusTag === "",
        statusTag: statusTag || null,
        endTime: (endTime == "") ? null : new Date(endTime),
  
        name, description, itemAmount,
      }).then(() => {
        markStale("project", "task");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else if (deletion) {
      stuffLogClient.deleteTask(task.id).then(() => {
        markStale("goal", "project", "task");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    } else {
      stuffLogClient.updateTask(task.id, {
        endTime: (endTime == "") ? null : new Date(endTime),
        clearEndTime: endTime == "",
        active: statusTag === "",
        statusTag: statusTag || null,
        clearStatusTag: statusTag === "",
        projectId: (projectId !== task.projectId) ? projectId : null,

        itemId, name, description, itemAmount,
      }).then(() => {
        markStale("goal", "project", "task", "log");
        modalStore.close();
      }).catch(err => {
        error = err.message ? err.message : err.toString();
      }).finally(() => {
        loading = false;
      })
    }
  }
</script>

<Modal show title="{verb} Task" error={error} closable on:close={modalStore.close}>
  <form on:submit|preventDefault={onSubmit}>
    <label for="projectName">Project</label>
    <ProjectSelect disabled={deletion || creation} name="projectName" bind:value={projectId} />
    <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="itemId">Item</label>
    <ItemSelect disabled={deletion || task.logs.length > 0} name="itemId" bind:value={itemId} />
    <label for="itemAmount">Amount</label>
    <input disabled={deletion} name="itemAmount" type="number" bind:value={itemAmount} />
    <label for="endTime">Deadline (Optional)</label>
    <DeadlineSelect disabled={deletion} bind:value={endTime} />
    <label for="statusTag">Status</label>
    <StatusTagSelect disabled={deletion} bind:value={statusTag} />
    
    <hr />

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