<script lang="ts">
  import type Project from "../models/project";
  import projectStore from "../stores/project";
import projectGroupStore from "../stores/projectGroup";
  interface OptGroup {
    status: string
    projects: Project[]
  }

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

  $: {
    let projects = $projectStore.projects;
    let labels = {};
    if (groupId != "") {
      const group = $projectGroupStore.groups.find(g => g.id === groupId);
      if (group != null) {
        projects = group.projects;
        labels = group.categoryNames;

        if (forceGroup && !group.projects.find(p => p.id === value)) {
          value = "";
        }
      }
    } else if (forceGroup) {
      value = "";
    }

    optGroups = [
      {
        status: labels["deadlines"] || "Deadlines",
        projects: projects.filter(p => p.active && p.endTime)
      },
      {
        status: labels["active"] || "Active",
        projects: projects.filter(p => p.active && !p.endTime)
      },
      {
        status: labels["progress"] || "Progress",
        projects: projects.filter(p => !p.active && p.statusTag === "progress")
      },
      {
        status: labels["background"] || "Background",
        projects: projects.filter(p => !p.active && p.statusTag === "background")
      },
      {
        status: labels["to do"] || "To Do",
        projects: projects.filter(p => !p.active && p.statusTag === "to do")
      },
      {
        status: labels["on hold"] || "On Hold",
        projects: projects.filter(p => !p.active && p.statusTag === "on hold")
      },
      {
        status: labels["completed"] || "Completed",
        projects: projects.filter(p => !p.active && p.statusTag === "completed")
      },
      {
        status: labels["failed"] || "Failed",
        projects: 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}>{$projectStore.loading ? "Loading..." : "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.tags.length ? `${project.tags[0]}: ${project.name}` : project.name}</option>
        {/each}
      </optgroup>
    {/if}
  {/each}
</select>