<script lang="ts">
  import groupStore from "../stores/group";

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

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

  $: {
    if (!disabled && $groupStore.groups.length > 0 && value === "") {
      const nonEmpty = $groupStore.groups.find(g => g.items.length > 0);
      if (nonEmpty != null) {
        value = nonEmpty.id;
      } else {
        value = $groupStore.groups[0].id;
      }
    }
  }
</script>

<select disabled={disabled || $groupStore.loading} name={name} bind:value={value}>
  {#each $groupStore.groups as group (group.id)}
    <option value={group.id} selected={group.id === value}>{group.name} ({group.items.length} items)</option>
  {/each}
</select>