<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 Icon from "./Icon.svelte";
  import ItemLink from "./ItemLink.svelte";
import Markdown from "./Markdown.svelte";
  import Option from "./Option.svelte";
  import OptionRow from "./OptionRow.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>

<ChildEntry entry={task}>
  <div slot="icon" class="icon" class:done={!task.active}>
    {#if !task.active}
      <span class="on"><Icon block name="check" /></span>
      <span class="off">
        {task.completedAmount}&nbsp;/&nbsp;{task.itemAmount}
      </span>
    {:else}
      {task.completedAmount}&nbsp;/&nbsp;{task.itemAmount}
    {/if}
  </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>

<style>
  div.icon {
    display: flex;
    flex-direction: column;
    font-size: 1em;
    padding: 0.2em .5ch;

    margin-right: 0.5em;
    background: #444;
    color: #CCC;
  }
  div.icon.done {
    padding-top: 0.285em;
    padding-bottom: 0.115em;

    background: #484;
    color: #78ff78;
  }
  div.icon.done span.off {
    display: none;
  }
  div.icon.done:hover {
    padding-top: 0.2em;
    padding-bottom: 0.2em;
  }
  div.icon.done:hover span.on {
    display: none;
  }
  div.icon.done:hover span.off {
    display: inline;
  }

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