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

  const setupName = new URLSearchParams(location.search).get("name");
  const isDev = ((globalThis as any).isDev = "hot" in import.meta);
  let name = localStore("name", "", identity, identity);
  if (setupName) name.set(setupName);
  let useMusic = isDev
    ? localStore(
        "useMusic",
        false,
        (v) => v == "true",
        (v) => v.toString(),
      )
    : readable(false);
  let micVolume = localStore("micVolume", 0.4, parseFloat, (v) => v.toString());
  let muted = localStore(
    "muted",
    false,
    (v) => v == "true",
    (v) => v.toString(),
  );
  let globalSpeak = localStore(
    "globalSpeak",
    true,
    (v) => v == "true",
    (v) => v.toString(),
  );
  let client: Client = $state(undefined as any);
  let players: Writable<Record<number, Player>> = undefined as any;
  let connected = $state(false);
  let ac: AudioManager;
  let wyrm: HTMLAudioElement;
  let outputAudio: HTMLDivElement;
  async function audioPrep() {
    let media;
    if ($useMusic) {
      media = wyrm;
    } else {
      media = await navigator.mediaDevices.getUserMedia({
        audio: {
          autoGainControl: false,
          noiseSuppression: true,
        },
        video: false,
      });
    }
    ac = new AudioManager(media, micVolume, muted);
  }
  async function connect() {
    if (client) {
      if (get(client.connected)) {
        return;
      }
      client.close();
    }
    await audioPrep();
    client = await Client.connect(
      readonly(name),
      readonly(globalSpeak),
      ac,
      outputAudio,
    );
    players = client.players;
    players.subscribe(() => {
      console.log("players", $players);
      players = client.players;
    });
    client.connected.subscribe(() => {
      connected = true;
    });
    console.log(client);
  }
</script>

{#if "WebTransport" in globalThis}
  <div bind:this={outputAudio}>{void 0}</div>

  <div class="controls">
    <div>
      I am <input
        type="text"
        maxlength="32"
        list="connectedPlayers"
        bind:value={$name}
      />
    </div>
    <div>
      <label for="micVolume">Mic Volume: </label>
      <input
        id="micVolume"
        type="range"
        min="0"
        max="1"
        step="0.1"
        bind:value={$micVolume}
      />
    </div>
    <div>
      <label for="muted">Muted: </label>
      <input id="muted" type="checkbox" bind:checked={$muted} />
    </div>
    <div>
      <label for="globalSpeak">Global Mic: </label>
      <input id="globalSpeak" type="checkbox" bind:checked={$globalSpeak} />
    </div>
    <div>
      <button onclick={() => connect()}>Connect</button>
    </div>
    {#if isDev}
      <div>
        <label for="useMusic">Use Music (dev only!)</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
        >
      </div>
    {/if}
  </div>
  {#if connected}
    <input type="checkbox" disabled bind:checked={connected} />
    <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>
    .controls {
      display: flex;
      flex-basis: 1 1 auto;
      flex-direction: column;
    }
    .name {
      font-style: italic;
    }
  </style>
{:else}
  !secureContext... was the correct link shared? <a
    href="chrome://flags/#unsafely-treat-insecure-origin-as-secure"
    >make sure you have the insecure flag set in case you need it</a
  >
  to <b>{window.location}</b>
{/if}
