<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 { readable, readonly, type Writable } from "svelte/store";

  const isDev = ((globalThis as any).isDev = location.pathname.includes("dev"));
  let name = localStore("name", "", identity, identity);
  let useMusic = isDev
    ? localStore(
        "useMusic",
        false,
        (v) => v == "true",
        (v) => v.toString()
      )
    : readable(false);
  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}
  />
  <button onclick={() => connect()}>Connect</button>
  {#if isDev}
    <label for="useMusic">Use Music</label>
    <input id="useMusic" type="checkbox" bind:checked={$useMusic} />
    <audio bind:this={wyrm} src="/wyrmjewelbox.wav" autoplay={false} controls
      >audio of the wyrm's houseki box</audio
    >
  {/if}
</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>
