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

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

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

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

<select name={name} bind:value={value} disabled={disabled || $groupStore.loading}>
  {#if optional}
    <option value={""} selected={"" === value}>None</option>
  {/if}
  {#each $groupStore.groups as group (group.id)}
    <optgroup label={group.name}>
      {#if enableWholeGroup}
        <option value={group.items.map(it => it.id).join(",")}>All "{group.name}" items</option>
      {/if}
      {#each group.items as item (item.id)}
        <option value={item.id} selected={item.id === value}>{item.name} ({item.groupWeight})</option>
      {/each}
    </optgroup>
  {/each}
</select>