'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var env_env = require('../env/env.js');

/**
 * 写入持久化存储localStorage。仅用于浏览器端，value里不能有循环引用
 * @param {string} key 键
 * @param {string} value 值
 * @param {number} expireMsec 过期时间，单位毫秒
 * @returns {boolean} 是否存储成功
 *
 * @example
 * const res = savePersist('name', 'mike', 30 * 86400 * 1000); // true
 * const name = getPersist('name'); // mike
 *
 * clearPersist('name'); // true
 * const name2 = getPersist('name'); // undefined
 */
function savePersist(key, value) {
  var expireMsec = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  if (env_env.checkNodeEnv()) {
    return false;
  }
  if (!window.localStorage || typeof window.localStorage === 'undefined') {
    return false;
  }
  var data = '';
  try {
    data = JSON.stringify(value);
  } catch (err) {
    console.error(err);
  }
  if (!data) {
    return false;
  }
  if (!expireMsec) expireMsec = 30 * 86400 * 1000;
  localStorage["vue_da|".concat(key)] = data; // 数据
  localStorage["vue_ep|".concat(key)] = Date.now() + expireMsec; // 对应失效时间
  return true;
}
/**
 * 读取持久化存储
 * @param {string} key
 * @returns {string} key对应的值
 * @example
 * ```ts
 * savePersist('name', 'mike');
 * getPersist('name'); // 'mike'
 *
 * // 已过期或不存在返回 undefined
 * getPersist('not-exist'); // undefined
 * ```
 */
function getPersist(key) {
  if (env_env.checkNodeEnv()) {
    return undefined;
  }
  if (!window.localStorage || typeof window.localStorage === 'undefined') {
    return undefined;
  }
  if (localStorage["vue_ep|".concat(key)] < Date.now()) {
    delete localStorage["vue_ep|".concat(key)];
    delete localStorage["vue_da|".concat(key)];
    return undefined;
  }
  var data = undefined;
  try {
    data = JSON.parse(localStorage["vue_da|".concat(key)]);
  } catch (err) {
    data = undefined;
    delete localStorage["vue_ep|".concat(key)];
    delete localStorage["vue_da|".concat(key)];
  }
  // 顺便清理一下其它可能过期的
  clearPersist();
  return data;
}
/**
 * 持久化存储。清理。传 key 就删除。不传清理所有过期的。
 * @param {string} [key]
 * @returns {boolean} 是否清楚成功
 * @example
 * ```ts
 * // 清理指定 key
 * clearPersist('name');
 *
 * // 不传参数时，清理所有已过期的数据
 * clearPersist();
 * ```
 */
function clearPersist(key) {
  if (env_env.checkNodeEnv()) {
    return false;
  }
  if (!window.localStorage || typeof window.localStorage === 'undefined') {
    return false;
  }
  if (key) {
    delete localStorage["vue_ep|".concat(key)];
    delete localStorage["vue_da|".concat(key)];
  } else {
    Object.keys(localStorage).forEach(function (i) {
      // if (localStorage.hasOwnProperty(i)) {
      if (i.indexOf('vue_ep|') === 0 && localStorage[i] < Date.now()) {
        delete localStorage[i];
        delete localStorage["vue_da".concat(i.slice(6))];
      }
      // }
    });
  }
  return true;
}

exports.clearPersist = clearPersist;
exports.getPersist = getPersist;
exports.savePersist = savePersist;
