import { removeDoubleSlash } from "../../../utils/url.js";
const APP_STYLE_ID_PREFIX = "emui-style-";
const addStylesToDOM = ({ name, hostUrl, documentEle }, fileName, index) => {
  if (!hostUrl)
    throw new Error("Unable to add styles to DOM. hostUrl is required.");
  return new Promise((resolve, reject) => {
    const ele = documentEle.createElement("link");
    if (!ele) reject(new Error("Unable to insert Application styles."));
    ele.id = `${APP_STYLE_ID_PREFIX}${name}-${index}`;
    ele.rel = "stylesheet";
    const url = new URL(fileName, hostUrl);
    ele.href = removeDoubleSlash(url.href);
    ele.onload = resolve.bind(null, ele.id);
    documentEle.head.appendChild(ele);
  });
};
const removeStyleFromDOM = (elementId = "", documentEle = document) => new Promise((resolve) => {
  const ele = documentEle.getElementById(elementId);
  if (!ele) console.warn(new Error(`style with id ${elementId} not found`));
  ele.remove();
  resolve();
});
const removeDynamicImportedStyles = (hostUrl, documentEle) => {
  const hostPattern = new RegExp(hostUrl, "i");
  const prefetchElements = documentEle.querySelectorAll('[rel="stylesheet"]');
  for (let index = prefetchElements.length - 1; index >= 0; index -= 1) {
    const ele = prefetchElements[index];
    const { href } = ele;
    if (hostPattern.test(href)) ele.remove();
  }
};
export {
  APP_STYLE_ID_PREFIX,
  addStylesToDOM,
  removeDynamicImportedStyles,
  removeStyleFromDOM
};
