import global from './global';
import baseUtil from '../utils/base';
import { callAPI } from './core/callManager'
import errUtil from '../utils/error';
import { sysLogger } from './logger';

const tryCallAPI = async function (api, ...params) {
  return callAPI(() => {
    const { localStorage } = global.platform.adapter || {};
    return localStorage && localStorage[api] && localStorage[api].bind(localStorage)
  }, 'localStorage', api, params);
}

/**
 * 本地存储
 */
const storage = {
  /**
   * 获取存储信息
   * @param {string} key 存储的key
   */
  async getItem(key) {
    const str = await tryCallAPI('getItem', key);
    return baseUtil.toObject(str);
  },

  /**
   * 设置存储信息
   * @param {string} key 存储的key
   * @param {any} value 存储的值
   */
  async setItem(key, value) {
    const str = baseUtil.toString(value);
    return await tryCallAPI('setItem', key, str);
  },

  /**
   * 移除存储信息
   * @param {string} key 存储的key
   */
  async removeItem(key) {
    return await tryCallAPI('removeItem', key);
  },

  /**
   * 清除本地缓存
   */
  async clear() {
    return await tryCallAPI('clear');
  },
}

export default errUtil.catchModuleErrStack(storage, sysLogger)