<script lang="ts">
  import type Project from "../models/project";
  import projectStore from "../stores/project";

  interface OptGroup {
    status: string
    projects: Project[]
  }

  export let value = "";
  export let name = "";
  export let disabled = false;
  export let optional = false;
  
  let optGroups: OptGroup[]

  $: {
    optGroups = [
      {
        status: "Deadlines",
        projects: $projectStore.projects.filter(p => p.active && p.endTime)
      },
      {
        status: "Active",
        projects: $projectStore.projects.filter(p => p.active && !p.endTime)
      },
      {
        status: "To Do",
        projects: $projectStore.projects.filter(p => !p.active && p.statusTag === "to do")
      },
      {
        status: "On Hold",
        projects: $projectStore.projects.filter(p => !p.active && p.statusTag === "on hold")
      },
      {
        status: "Completed",
        projects: $projectStore.projects.filter(p => !p.active && p.statusTag === "completed")
      },
      {
        status: "Background",
        projects: $projectStore.projects.filter(p => !p.active && p.statusTag === "background")
      },
      {
        status: "Progress",
        projects: $projectStore.projects.filter(p => !p.active && p.statusTag === "progress")
      },
      {
        status: "Failed",
        projects: $projectStore.projects.filter(p => !p.active && p.statusTag === "failed")
      },
    ]

    for (const group of optGroups) {
      group.projects.sort((a,b) => a.name.localeCompare(b.name));
    }
  }

  $: {
    if (optGroups.length > 0 && value === "" && !optional) {
      const nonEmpty = optGroups.find(g => g.projects.length > 0);
      if (nonEmpty != null) {
        value = nonEmpty.projects[0].id;
      }
    }
  }
</script>

<select name={name} bind:value={value} disabled={disabled || $projectStore.loading}>
  {#if optional}
    <option value={""} selected={"" === value}>None</option>
  {/if}
  {#each optGroups as group (group.status)}
    {#if group.projects.length > 0}
      <optgroup label={group.status}>
        {#each group.projects as project (project.id)}
          <option value={project.id} selected={project.id === value}>{project.name}</option>
        {/each}
      </optgroup>
    {/if}
  {/each}
</select>