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 = function (api, ...params) {
  return callAPI(() => {
    const { storage } = global.platform.adapter || {};
    const { getStorage } = storage || {};
    const module = (baseUtil.isFun(getStorage) ? getStorage() : storage) || {};
    return module[api] && module[api].bind(module)
  }, 'storage', api, params)
}

/**
 * 并不是本地存储，存在后台的持久化！！！
 */
const storage = {
  /**
   * 获取存储信息
   * @param {string} key 存储的key
   */
  getItem(key) {
    return tryCallAPI('getItem', key);
  },

  /**
   * 设置存储信息
   * @param {string} key 存储的key
   * @param {any} value 存储的值
   */
  setItem(key, value) {
    return tryCallAPI('setItem', key, value);
  },

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

  /**
   * 所有存储的键值
   */
  getKeys() {
    return tryCallAPI('getKeys');
  }
}

export default errUtil.catchModuleErrStack(storage, sysLogger)
