<script lang="ts">
  import { onMount } from "svelte";
  import { Client, Player } from "$lib/client";
  import { AudioManager } from "$lib/audio";
  import { identity, localStore } from "$lib/stores";
  import { readonly, type Writable } from "svelte/store";

  let name = localStore("name", "", identity, identity);
  let useMusic = localStore(
    "useMusic",
    false,
    (v) => v == "true",
    (v) => v.toString()
  );
  let client: Client = $state(undefined as any);
  let players: Writable<Record<number, Player>> = undefined as any;
  let ac: AudioManager;
  let wyrm: HTMLAudioElement;
  let outputAudio: HTMLDivElement;
  async function audioPrep() {
    let media = $useMusic
      ? wyrm
      : await navigator.mediaDevices.getUserMedia({
          audio: true,
          video: false,
        });
    ac = new AudioManager(media);
  }
  async function connect() {
    await audioPrep();
    client = await Client.connect(readonly(name), ac, outputAudio);
    players = client.players;
    console.log(client);
  }
</script>

<div bind:this={outputAudio}>audio outputs</div>

<div>
  I am <input
    type="text"
    maxlength="32"
    list="connectedPlayers"
    bind:value={$name}
  />
  <label for="useMusic">Use Music</label>
  <input id="useMusic" type="checkbox" bind:checked={$useMusic} />
  <button onclick={() => connect()}>Connect</button>
  <audio bind:this={wyrm} src="/wyrmjewelbox.wav" autoplay={false} controls
    >audio of the wyrm's houseki box</audio
  >
</div>
{#if client !== undefined}
  <datalist>
    {#each Object.values($players) as player}
      <option>{player.name}</option>
    {/each}
  </datalist>
  <div>
    Connected players - {Object.values($players).length}<br />
    {#each Object.values($players) as player}
      <pre class="name">{player.name}</pre>
    {/each}
  </div>
{/if}

<style>
  .name {
    font-style: italic;
  }
</style>
