import React from 'react';
import { SocketEmitter } from '@zenview/micro-utils';
import './index.less';

function registerIconFont(scriptUrl) {
  if (!window._ICON_IS_INIT_) {
    window._ICON_SCRIPT_URL = scriptUrl;
    window._ICON_IS_INIT_ = true;
    loadScript(scriptUrl)
      .then(() => {
        SocketEmitter.emit('update-iconfont');
      })
      .catch(e => {
        console.error(e);
        window._ICON_IS_INIT_ = false;
      });
  }
}

function loadScript(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    document.body.appendChild(script);
    script.addEventListener('load', () => {
      resolve();
    });
    script.addEventListener('error', err => {
      reject(err);
    });
  });
}

function IconFont({ type, className = '', ...props }) {
  return (
    <i className={`anticon ${className}`} {...props}>
      <svg width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false">
        <use xlinkHref={`#${type}`} />
      </svg>
    </i>
  );
}

IconFont.registerIconFont = registerIconFont;

export default IconFont;
