"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
var _Storage = _interopRequireDefault(require("./Storage"));
function _interopRequireDefault(e) {
  return e && e.__esModule ? e : {
    default: e
  };
}
const LocalDatastoreController = {
  async fromPinWithName(name) {
    const values = await _Storage.default.getItemAsync(name);
    if (!values) {
      return [];
    }
    const objects = JSON.parse(values);
    return objects;
  },
  pinWithName(name, value) {
    const values = JSON.stringify(value);
    return _Storage.default.setItemAsync(name, values);
  },
  unPinWithName(name) {
    return _Storage.default.removeItemAsync(name);
  },
  async getAllContents() {
    const keys = await _Storage.default.getAllKeysAsync();
    return keys.reduce(async (previousPromise, key) => {
      const LDS = await previousPromise;
      if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
        const value = await _Storage.default.getItemAsync(key);
        try {
          LDS[key] = JSON.parse(value);
        } catch (error) {
          console.error('Error getAllContents: ', error);
        }
      }
      return LDS;
    }, Promise.resolve({}));
  },
  // Used for testing
  async getRawStorage() {
    const keys = await _Storage.default.getAllKeysAsync();
    return keys.reduce(async (previousPromise, key) => {
      const LDS = await previousPromise;
      const value = await _Storage.default.getItemAsync(key);
      LDS[key] = value;
      return LDS;
    }, Promise.resolve({}));
  },
  async clear() {
    const keys = await _Storage.default.getAllKeysAsync();
    const toRemove = [];
    for (const key of keys) {
      if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
        toRemove.push(key);
      }
    }
    const promises = toRemove.map(this.unPinWithName);
    return Promise.all(promises);
  }
};
module.exports = LocalDatastoreController;
var _default = exports.default = LocalDatastoreController;