<script lang="ts">
  import type { GoalResult } from "../models/goal";
  import type { ModalData } from "../stores/modal";
  import Option from "./Option.svelte";
  import OptionRow from "./OptionRow.svelte";
  import ParentEntry from "./ParentEntry.svelte";
  import Progress from "./Progress.svelte";

  export let goal: GoalResult = null;
  export let showAllOptions = false;
  export let linkGoal = false;

  let mdGoalEdit: ModalData;
  let mdGoalDelete: ModalData;
  let msLength: number;
  let msElapsed: number;

  $: mdGoalEdit = {name:"goal.edit", goal};
  $: mdGoalDelete = {name:"goal.delete", goal};

  $: {
    const now = Date.now()
    const start = Date.parse(goal.startTime)
    const length = Date.parse(goal.endTime) - start;

    msLength = length;
    msElapsed = 0;

    if (now > start) {
      if (now > start + length) {
        msElapsed = length;
      } else {
        msElapsed = Math.round(now - start);
      }
    }
  }
</script>

<ParentEntry
  full={showAllOptions} 
  entry={goal} 
  headerLink={linkGoal ? "/goals#"+goal.id : ""}
>
  {#if showAllOptions}
    <OptionRow>
      <Option open={mdGoalEdit}>Edit</Option>
      <Option open={mdGoalDelete}>Delete</Option>
    </OptionRow>
  {/if}
  <div class="progress">
    <Progress count={goal.completedAmount} target={goal.amount} />
    <Progress thinner gray count={msElapsed} target={msLength} />
  </div>
</ParentEntry>
<style>
  div.progress {
    padding-top: 0.125em;
    font-size: 1.25em;
  }
</style>