'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var isStr = _interopDefault(require('./isStr'));
var getStringHash = _interopDefault(require('./getStringHash'));
var _shared = require('./_shared');

/**
 * 动态插入脚本到head中
 * @param {string} script
 * @param {boolean} reload
 *
 * insertScript('console.log("hello b-utils")');
 */
function insertScript(script, reload) {
  return new Promise(function (resolve) {
    script = isStr(script) ? script : '';
    var scriptId = "bs_txt_".concat(getStringHash(script));
    _shared.cachedStyleOrScript(scriptId, reload, false).then(function (cached) {
      if (cached) return resolve();
      var scriptEl = document.createElement('script');
      scriptEl.type = 'text/JavaScript';
      scriptEl.id = scriptId;

      try {
        scriptEl.appendChild(document.createTextNode(script));
      } catch (e) {
        scriptEl.text = script;
      }

      document.querySelector('head').appendChild(scriptEl);
      setTimeout(function () {
        return resolve();
      });
    });
  }).then();
}

module.exports = insertScript;
