<script lang="ts">
  import type { ProjectResult } from "../models/project";
  import selectionStore from "../stores/selection";
  import ProjectEntry from "./ProjectEntry.svelte";
  import QlList from "./QLList.svelte";

  export let projects: ProjectResult[];

  let expiringProjects: ProjectResult[];
  let activeProjects: ProjectResult[];
  let inactiveProjects: ProjectResult[];
  let completedProjects: ProjectResult[];
  let failedProjects: ProjectResult[];
  let onholdProjects: ProjectResult[];
  let ideaProjects: ProjectResult[];
  let project: ProjectResult = null;

  $: project = $selectionStore.hash.startsWith("P") ? projects.find(p => p.id === $selectionStore.hash) : null;
  $: expiringProjects = projects.filter(p => p.active && p.endTime).sort((a,b) => Date.parse(a.endTime) - Date.parse(b.endTime));
  $: activeProjects = projects.filter(p => p.active && !p.endTime).sort((a,b) => a.name.localeCompare(b.name));
  $: inactiveProjects = projects.filter(p => !p.active).sort((a,b) => a.name.localeCompare(b.name));
  $: completedProjects = inactiveProjects.filter(p => p.statusTag === "completed" || p.statusTag == null);
  $: failedProjects = inactiveProjects.filter(p => p.statusTag === "failed" || p.statusTag === "declined");
  $: onholdProjects = inactiveProjects.filter(p => p.statusTag === "on hold" || p.statusTag === "onhold");
  $: ideaProjects = inactiveProjects.filter(p => p.statusTag === "to do" || p.statusTag === "idea");

  $: {
    if (project === null && projects.length > 0) {
      project = expiringProjects[0] || activeProjects[0] || completedProjects[0] || null;
      if (project !== null) {
        selectionStore.change("hash", project.id);
      }
    }
  }
</script>

<div class="quest-log">
  <div class="list">
    <QlList label="Deadlines" projects={expiringProjects} />
    <QlList label="Active" projects={activeProjects} />
    <QlList label="To Do" projects={ideaProjects} />
    <QlList label="On Hold" projects={onholdProjects} />
    <QlList label="Completed" projects={completedProjects} />
    <QlList label="Failed" projects={failedProjects} />
  </div>
  <div class="body">
    {#if project != null}
      <ProjectEntry hideIcon project={project} showAllOptions />
    {/if}
  </div>
</div>

<style>
  div.quest-log {
    display: flex;
    flex-direction: row;
  }

  div.list {
    flex-shrink: 0;
    width: 32ch;
  }

  div.body {
    flex-grow: 1;
    margin: 1em 1ch;
  }
</style>