import 'kit_logger';
// eslint-disable-next-line no-undef
const Logger = logger('Storage');
function Storage(namespace) {
  const argument =
    // eslint-disable-next-line prefer-rest-params
    arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
  this.MAX_SIZE = argument.max || 128;
  this.namespace = namespace;
  this.list = [];
  localStorage && (this.list = this.init());
}

Storage.prototype.init = function() {
  try {
    return JSON.parse(localStorage.getItem(this.namespace) || '[]');
  } catch (e) {
    return [];
  }
};

Storage.prototype.get = function(key) {
  return this.list.find(item => item.key === key);
};

Storage.prototype.set = function(key, value) {
  const data = {
    key,
    data: value,
  };

  if (this.list.length < this.MAX_SIZE) {
    this.list.push(data);
  } else {
    // eslint-disable-next-line no-bitwise
    const size = ~~(Math.random() * this.MAX_SIZE);
    this.list[size] = data;
  }
  try {
    localStorage.setItem(this.namespace, JSON.stringify(this.list));
  } catch (e) {
    Logger.warn(e);
  }
};

Storage.prototype.clear = function() {
  return localStorage.removeItem(this.namespace);
};

export default Storage;
