<script context="module">
  import { createEventDispatcher, onMount } from "svelte";
  import { Mutex } from "$/client/helpers.js";

  // this prevents loading it multiple times
  const ready = {};
  const lock = new Mutex();

  export const inject_remote = async (document, src, ready_cb=undefined) => {
    if(ready[src]) {
      // no need to lock, it's done already
      if(ready_cb) ready_cb();
    } else {
      // locking time, maybe it's not ready
      await lock.hold();

      if(ready[src]) {
        // looks like someone else did it already, done
        lock.release();
        if(ready_cb) ready_cb();
      } else {
        // nope, not really ready, so we must be first
        let head = document.getElementsByTagName('head')[0];
        let script = document.createElement('script');

        script.onload = async () => {
          ready[src] = true;
          // script came back and we signal it's ready, unlock
          lock.release();
          if(ready_cb) ready_cb();
        }

        script.src = src;
        script.type = 'text/javascript';

        head.append(script);
      }
    }

    await lock.wait();
  }
</script>

<script>
  export let src = "";
  const dispatch = createEventDispatcher();

  onMount(async () => {
    await inject_remote(document, src, () => {
      dispatch("load");
    });
  });
</script>
