<script lang="ts">
  import type { GroupResult } from "../models/group";

  export let value = "";
  export let name = "";
  export let disabled = false;
  export let optional = false;
  export let optionalLabel = "None";
  export let group: GroupResult = null;

  $: {
    if (group != null && !group.items.find(t => t.id === value)) {
      if (optional) {
        value = "";
      } else {
        value = group.items[0]?.id || "";
      }
    }
  }
</script>

<select name={name} bind:value={value} disabled={disabled || group == null || group.items.length === 0}>
  {#if optional}
    <option value={""} selected={"" === value}>{optionalLabel}</option>
  {/if}
  {#if group != null}
    {#each group.items as item (item.id)}
      <option value={item.id} selected={item.id === value}>{item.name} ({item.groupWeight})</option>
    {/each}
  {/if}
</select>