<script context="module">
  export const DIAL = {};
</script>

<script lang="ts">
  import {
    setContext,
    onDestroy,
    createEventDispatcher,
    afterUpdate,
  } from "svelte";
  import type { NailState } from "./Nail.svelte";
  import type { Writable } from "svelte/store";

  let states: Writable<NailState>[] = [];

  let visible = false;

  export let dist = 82;

  export let angleRange = [0, 360];

  let self;

  const updateNails = () => {
    const pi = (angleRange[1] - angleRange[0]) / states.length;
    for (let i = 0; i < states.length; ++i) {
      states[i].set({
        angle: pi * i + angleRange[0],
        length: dist,
        visible,
      });
    }
  };

  setContext(DIAL, {
    registerNail(nail: Writable<NailState>) {
      states.push(nail);
      updateNails();
      onDestroy(() => {
        const i = states.indexOf(nail);
        console.log("destroy at ", i);
        states.splice(i, 1);
        updateNails();
      });
    },
  });

  afterUpdate(() => {
    updateNails();
  });
</script>

<div
  bind:this={self}
  on:click={() => {
    visible = !visible;
    updateNails();
  }}
  class="dial"
>
  <slot />
</div>

<style>
  .dial {
    padding: 10px;
    border: 1px solid;
    border-radius: 99px;
    width: 25px;
    height: 25px;
    cursor: pointer;
  }
</style>
