<script lang="ts">
  import type { ProjectResult } from "../models/project";
  import type { ModalData } from "../stores/modal";
  import Option from "./Option.svelte";
  import OptionRow from "./OptionRow.svelte";
  import ParentEntry from "./ParentEntry.svelte";
  import TaskEntry from "./TaskEntry.svelte";

  export let project: ProjectResult = null;
  export let showAllOptions: boolean = false;
  export let hideInactive: boolean = false;
  export let linkProject: boolean = false;

  let mdAddTask: ModalData;
  let mdProjectEdit: ModalData;
  let mdProjectDelete: ModalData;
  let progressAmount: number;
  let progressTarget: number;

  $: mdAddTask = {name:"task.add", project};
  $: mdProjectEdit = {name:"project.edit", project};
  $: mdProjectDelete = {name:"project.delete", project};
  $: progressAmount = project.tasks.map(t => t.active 
    ? Math.min(t.completedAmount, t.itemAmount) * t.item.groupWeight 
    : t.itemAmount * t.item.groupWeight
  ).reduce((n,m) => n+m, 0);
  $: progressTarget = Math.max(project.tasks.map(t => t.itemAmount * t.item.groupWeight).reduce((n,m) => n+m, 0), 1);
</script>

<ParentEntry 
  full={showAllOptions} 
  entry={project} 
  headerLink={linkProject ? "/projects#"+project.id : ""}
  progressAmount={progressAmount}
  progressTarget={progressTarget}
>
  {#if showAllOptions}
    <OptionRow>
      <Option open={mdAddTask}>Add Task</Option>
      <Option open={mdProjectEdit}>Edit</Option>
      <Option open={mdProjectDelete}>Delete</Option>
    </OptionRow>  
  {/if}
  {#each project.tasks as task (task.id)}
    {#if !hideInactive || task.active}
      <TaskEntry showAllOptions={showAllOptions} task={task} project={project} />
    {/if}
  {/each}
</ParentEntry>