<script lang="ts">
  import { onMount } from "svelte";
  import { Client } from "$lib/client.svelte.ts";
  import { AudioManager } from "$lib/audio.svelte.ts";
  import { BinaryStreamReader } from "$lib/binary/readerStream";

  let name = $state("");
  let useMusic = $state(false);
  let client: Client = $state(undefined as any);
  let players = $derived.by(() => {
    if (client === undefined) return {};
    return client.players;
  });
  let ac: AudioManager;
  let wyrm: HTMLAudioElement;
  let outputAudio: HTMLDivElement;
  async function a() {
    name = localStorage.getItem("name") ?? "";
    useMusic = localStorage.getItem("useMusic") == "true";
  }
  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(ac, outputAudio);
    console.log(client);
  }

  onMount(a);
</script>

<div bind:this={outputAudio} />

<div>
  I am <input
    type="text"
    maxlength="32"
    list="connectedPlayers"
    bind:value={name}
    onchange={() => localStorage.setItem("name", name)}
  />
  <label for="useMusic">Use Music</label>
  <input
    id="useMusic"
    type="checkbox"
    bind:checked={useMusic}
    onchange={() => localStorage.setItem("useMusic", 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 players as player}
      <option>{player.name}</option>
    {/each}
  </datalist>
  <div>
    Connected players - {players.length}<br />
    {#each players as player}
      <pre class="name">{player.name}</pre>
    {/each}
  </div>
{/if}

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