import { noop } from "utils/noop";
import { defaultUnlayerScriptUrl } from "constants/unlayer";

const callbacks: (() => void)[] = [];

const isScriptInjected = (scriptUrl: string) => {
  const scripts = document.querySelectorAll("script");
  let injected = false;

  scripts.forEach((script) => {
    if (script.src.includes(scriptUrl)) {
      injected = true;
    }
  });

  return injected;
};

const addCallback = (callback: () => void) => {
  callbacks.push(callback);
};

const runCallbacks = () => {
  let callback;

  while ((callback = callbacks.shift())) {
    callback();
  }
};

export const loadScript = (
  callback: () => void = noop,
  scriptUrl = defaultUnlayerScriptUrl,
) => {
  addCallback(callback);

  if (!isScriptInjected(scriptUrl)) {
    const embedScript = document.createElement("script");
    embedScript.setAttribute("src", scriptUrl);
    embedScript.onload = () => {
      runCallbacks();
    };
    document.head.appendChild(embedScript);
  } else {
    runCallbacks();
  }
};
