"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
var _StorageController = _interopRequireDefault(require("./StorageController.react-native"));
function _interopRequireDefault(e) {
  return e && e.__esModule ? e : {
    default: e
  };
}
const LocalDatastoreController = {
  async fromPinWithName(name) {
    const values = await _StorageController.default.getItemAsync(name);
    if (!values) {
      return [];
    }
    const objects = JSON.parse(values);
    return objects;
  },
  async pinWithName(name, value) {
    try {
      const values = JSON.stringify(value);
      await _StorageController.default.setItemAsync(name, values);
    } catch (e) {
      // Quota exceeded, possibly due to Safari Private Browsing mode
      console.error(e.message);
    }
  },
  unPinWithName(name) {
    return _StorageController.default.removeItemAsync(name);
  },
  async getAllContents() {
    const keys = await _StorageController.default.getAllKeysAsync();
    const batch = [];
    for (let i = 0; i < keys.length; i += 1) {
      const key = keys[i];
      if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
        batch.push(key);
      }
    }
    const LDS = {};
    let results = [];
    try {
      results = await _StorageController.default.multiGet(batch);
    } catch (error) {
      console.error('Error getAllContents: ', error);
      return {};
    }
    results.forEach(pair => {
      const [key, value] = pair;
      try {
        LDS[key] = JSON.parse(value);
      } catch (error) {
        LDS[key] = null;
      }
    });
    return LDS;
  },
  // Used for testing
  async getRawStorage() {
    const keys = await _StorageController.default.getAllKeysAsync();
    const storage = {};
    const results = await _StorageController.default.multiGet(keys);
    results.map(pair => {
      const [key, value] = pair;
      storage[key] = value;
    });
    return storage;
  },
  async clear() {
    const keys = await _StorageController.default.getAllKeysAsync();
    const batch = [];
    for (let i = 0; i < keys.length; i += 1) {
      const key = keys[i];
      if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
        batch.push(key);
      }
    }
    await _StorageController.default.multiRemove(batch).catch(error => console.error('Error clearing local datastore: ', error));
  }
};
module.exports = LocalDatastoreController;
var _default = exports.default = LocalDatastoreController;