import { createVNode as _createVNode } from "vue";

function createScriptUrlElements(scriptUrls, index = 0) {
  const currentScriptUrl = scriptUrls[index];
  const script = document.createElement('script');
  script.setAttribute('src', currentScriptUrl);
  script.setAttribute('data-namespace', currentScriptUrl);

  if (scriptUrls.length > index + 1) {
    script.onload = () => {
      createScriptUrlElements(scriptUrls, index + 1);
    };

    script.onerror = () => {
      createScriptUrlElements(scriptUrls, index + 1);
    };
  }

  document.body.appendChild(script);
}

export default function create(options = {}) {
  const {
    scriptUrl,
    extraCommonProps
  } = options;

  if (Array.isArray(scriptUrl)) {
    // 因为iconfont资源会把svg插入before，所以前加载相同type会覆盖后加载，为了数组覆盖顺序，倒叙插入
    createScriptUrlElements(scriptUrl.reverse());
  } else {
    createScriptUrlElements([scriptUrl]);
  }

  const IconFont = props => {
    const {
      type
    } = props;
    return _createVNode("i", {
      "role": "img"
    }, [_createVNode("svg", null, [_createVNode("use", {
      "xlink:href": `#${type}`
    }, null)])]);
  };

  IconFont.props = {
    type: String
  };
  return IconFont;
}