"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var style_exports = {};
__export(style_exports, {
  APP_STYLE_ID_PREFIX: () => APP_STYLE_ID_PREFIX,
  addStylesToDOM: () => addStylesToDOM,
  removeDynamicImportedStyles: () => removeDynamicImportedStyles,
  removeStyleFromDOM: () => removeStyleFromDOM
});
module.exports = __toCommonJS(style_exports);
var import_url = require("../../../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 = (0, import_url.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();
  }
};
