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

/**
 * 动态插入样式到head中
 * @param {string} css
 * @param {boolean} reload
 *
 * @example
 * insertCss('body { color: blue; }');
 */
function insertCss(css, reload) {
  return new Promise(function (resolve) {
    css = isStr(css) ? css : '';
    var styleId = "bs_txt_".concat(getStringHash(css));
    cachedStyleOrScript(styleId, reload, true).then(function (cached) {
      if (cached) return resolve();
      var style = document.createElement('style');
      style.type = 'text/css';

      if (style.styleSheet) {
        var ieInsertCSS = function ieInsertCSS() {
          style.styleSheet.cssText = css;
          setTimeout(function () {
            return resolve();
          });
        };

        if (style.styleSheet.disable) {
          setTimeout(function () {
            return ieInsertCSS();
          }, 200);
        } else {
          ieInsertCSS();
        }
      } else {
        style.appendChild(document.createTextNode(css));
        document.querySelector('head').appendChild(style);
        setTimeout(function () {
          return resolve();
        });
      }
    });
  }).then();
}

export default insertCss;
