const LOAD_STYLE = (window.LOAD_STYLE = {});

const LOAD_SCRIPT = (window.LOAD_SCRIPT = {});

export function LoaderScript(src) {
  if (LOAD_SCRIPT[src]) {
    return Promise.resolve(LOAD_SCRIPT[src]);
  }
  return window.System.import(src).then((m) => {
    LOAD_SCRIPT[src] = m;
    return m;
  });
}

export function LoaderStyle(href) {
  if (LOAD_STYLE[href]) {
    return Promise.resolve();
  }
  return new Promise((resolve, reject) => {
    LOAD_STYLE[href] = true;
    let link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('type', 'text/css');
    link.setAttribute('href', href);
    link.addEventListener('load', () => {
      resolve();
    });
    link.addEventListener('error', (e) => {
      reject(e);
    });
    document.head.appendChild(link);
  });
}

export default async function LoaderModule({ script, style }) {
  await LoaderStyle(style);
  return await LoaderScript(script);
}
