import _JSON$stringify from "@babel/runtime-corejs2/core-js/json/stringify";
import { isServer } from '../_utils/constant';
let cacheName = 'gd-components';
const VERSION = '1.0.0';
const CACHE_TIME = 7 * 24 * 60 * 1000;

function changeTime(time) {
  if (typeof time === 'number') return time;

  if (typeof time === 'string' && /([.\d]+)([DdSsHhMm])$/.test(time)) {
    switch (RegExp.$2.toLocaleLowerCase()) {
      case 'd':
        return RegExp.$1 * 24 * 60 * 60 * 1000;

      case 'h':
        return RegExp.$1 * 60 * 60 * 1000;

      case 'm':
        return RegExp.$1 * 60 * 1000;

      case 's':
        return RegExp.$1 * 1000;

      default:
        break;
    }
  }

  console.error(`无效的缓存时间:${time}`); // eslint-disable-line

  throw new Error('无效的时间');
}

function createCache(api) {
  return {
    get(key, config = {}) {
      const {
        version = VERSION
      } = config;

      try {
        const root = JSON.parse(api.getItem(cacheName));

        if (root && root.data[key] && root.data[key].version == version) {
          // eslint-disable-line
          if (root.data[key].expires < new Date()) {
            this.remove(key);
            return undefined;
          }

          return root.data[key].data;
        }

        return undefined;
      } catch (error) {
        return undefined;
      }
    },

    set(key, data, config = {}) {
      const {
        version = VERSION,
        time = CACHE_TIME
      } = config;

      try {
        const d = JSON.parse(api.getItem(cacheName)) || {
          version,
          data: {}
        };
        d.data[key] = {
          version,
          data,
          expires: +new Date() + changeTime(time)
        };
        api.setItem(cacheName, _JSON$stringify(d));
        return true;
      } catch (error) {
        if (error.name === 'QuotaExceededError') {
          api.removeItem(cacheName);
          return this.set(key, data, config);
        }

        return false;
      }
    },

    clear() {
      try {
        api.removeItem(cacheName);
        return true;
      } catch (error) {
        return false;
      }
    },

    remove(key) {
      try {
        this.set(key, undefined);
        return true;
      } catch (error) {
        return false;
      }
    }

  };
}

let localStorage = null;
let sessionStorage = null;

if (isServer) {
  let noop = {
    getItem() {},

    setItem() {},

    removeItem() {}

  };
  localStorage = noop;
  sessionStorage = noop;
} else {
  localStorage = window.localStorage;
  sessionStorage = window.sessionStorage;
}

export function setPrefix(name) {
  cacheName = name;
}
export const localCache = createCache(localStorage);
export const sessionCache = createCache(sessionStorage);
export default {
  setPrefix,
  localCache,
  sessionCache
};