import getCache from './getCache';
import setCache from './setCache';
import { CACHED_STYLES, CACHED_SCRIPTS } from './consts';

/* eslint-disable import/prefer-default-export */

/**
 * 处理脚本缓存
 * @param {string} cacheId
 * @param {boolean} reload
 * @param {boolean} isStyle
 */
function cachedStyleOrScript(cacheId, reload, isStyle) {
  return new Promise(function (resolve) {
    reload = reload !== false;
    var cacheKey = isStyle ? CACHED_STYLES : CACHED_SCRIPTS;
    var caches = getCache(cacheKey) || [];

    if (!reload && caches.indexOf(cacheId) > -1) {
      return resolve(true);
    }

    var el = document.querySelector("#".concat(cacheId));
    if (el) el.parentNode.removeChild(el);
    caches = caches.filter(function (item) {
      return item !== cacheId;
    });
    caches.push(cacheId);
    setCache(cacheKey, caches);
    return resolve(false);
  });
}
/* eslint-enable import/prefer-default-export */

export { cachedStyleOrScript };
