"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.deleteStore = deleteStore;
exports.getStore = getStore;
exports.setStore = setStore;
require("core-js/modules/es.regexp.exec.js");
var _constants = require("./constants");
const separatorStr = '/@@/';
function deleteStore(key) {
  if (typeof window === 'undefined') {
    return;
  }
  try {
    window.localStorage.removeItem(`${_constants.prefix}${key}`);
  } catch (e) {
    console.error(e);
    // throw e
  }
}

/**
 * @param key
 * @param value 不传则表示删除
 * @param time  单位：秒
 */
function setStore(key, value, time) {
  if (typeof window === 'undefined') {
    return;
  }
  if (typeof value === 'undefined') {
    deleteStore(key);
    return;
  }
  try {
    let str = '';
    if (typeof value === 'object') {
      str = `${JSON.stringify(value)}`;
    } else {
      str = `${value}`;
    }
    const lastTime = time ? `${separatorStr}${Date.now() + time * 1000}` : '';
    window.localStorage.setItem(`${_constants.prefix}${key}`, `${str}${lastTime}`);
  } catch (e) {
    console.error(e);
    // throw e
  }
}

function getStore(key) {
  if (typeof window === 'undefined') {
    return '';
  }
  let str = '';
  try {
    str = window.localStorage.getItem(`${_constants.prefix}${key}`);
  } catch (e) {
    console.error(e);
    // throw e
  }

  if (str) {
    const arr = str.split(separatorStr);
    let value = arr[0];
    try {
      value = JSON.parse(arr[0]);
    } catch (e) {
      console.error(e);
      // throw e
    }

    const time = arr[1];
    if (time) {
      if (Date.now() <= +time) {
        return value;
      }
      deleteStore(key);
    }
    return value;
  }
  return '';
}