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

  export let value = "";
  export let name = "";
  export let disabled = false;
  export let optional = false;

  $: {
    if ($projectStore.stale && !$projectStore.loading) {
      projectStore.load({});
    }
  }

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

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