<script lang="ts">
  import type Project from "../models/project";
  import type { TaskResult } from "../models/task";
  import type { ModalData } from "../stores/modal";
  import ChildEntry from "./ChildEntry.svelte";
  import DateSpan from "./DateSpan.svelte";
  import ItemLink from "./ItemLink.svelte";
  import Markdown from "./Markdown.svelte";
  import Option from "./Option.svelte";
  import OptionRow from "./OptionRow.svelte";
  import StatusColor from "./StatusColor.svelte";
  import TaskIcon from "./TaskIcon.svelte";

  export let task: TaskResult = null;
  export let project: Project = null;
  export let showAllOptions: boolean = false;

  let showLogs = false;
  let mdLogAdd: ModalData;
  let mdTaskEdit: ModalData;
  let mdTaskDelete: ModalData;

  function toggleShowLogs() {
    showLogs = !showLogs;
  }

  $: mdLogAdd = {name: "log.add", task: {...task, project}};
  $: mdTaskEdit = {name: "task.edit", task: {...task, project}};
  $: mdTaskDelete = {name: "task.delete", task: {...task, project}};
</script>

<StatusColor affects="task" entry={task}>
  <ChildEntry entry={task}>
    <div slot="icon">
      <TaskIcon task={task} />
    </div>
    <ItemLink item={task.item} />
    <OptionRow>
      {#if task.logs.length > 0}
        <Option on:click={toggleShowLogs}>{showLogs ? "Hide Logs" : "Show Logs"}</Option>
      {/if}
      <Option open={mdLogAdd}>Add Log</Option>
      {#if showAllOptions}
        <Option open={mdTaskEdit}>Edit</Option>
        <Option open={mdTaskDelete}>Delete</Option>
      {/if}
    </OptionRow>
    {#if showLogs && task.logs.length > 0}
      <div class="log-list">
        {#each task.logs as log (log.id)}
          <div class="log">
            <div class="log-time"><DateSpan time={log.loggedTime} /></div>
            <div class="log-description">
              <Markdown source={log.description} />
            </div>
          </div>
        {/each}
      </div>
    {/if}
  </ChildEntry>
</StatusColor>

<style>
  div.log-list {
    padding: 0.5em 0;
  }
  div.log {
    padding: 0.25em 1ch;
  }
  div.log-time {
    font-size: 0.75em;
    font-weight: 800;
  }
</style>
