import isUrl from './isUrl';
import getStringHash from './getStringHash';
import { cachedStyleOrScript } from './_shared';

/**
 * 动态加载css文件
 * @param {string} href
 * @param {boolean} reload
 *
 * @example
 * loadCss('https://s1.hdslb.com/bfs/static/jinkela/long/laputa-css/light.css');
 */
function loadCss(href, reload) {
  return new Promise(function (resolve, reject) {
    if (!isUrl(href)) return reject(new Error('href不是一个正确的url地址！'));
    var styleId = "bs_url_".concat(getStringHash(href));
    cachedStyleOrScript(styleId, reload, true).then(function (cached) {
      if (cached) return resolve();
      var link = document.createElement('link');
      link.id = styleId;
      link.type = 'text/css';
      link.rel = 'stylesheet';
      link.href = href;
      document.querySelector('head').appendChild(link);
      setTimeout(function () {
        return resolve();
      });
    });
  }).then();
}

export default loadCss;
