"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = load;
exports.get = get;
exports.off = off;
exports.on = on;
exports.once = once;
exports.reset = reset;
exports.set = set;
exports.unset = unset;
var _events = _interopRequireDefault(require("events"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
 * Copyright 2020 The Kubernetes Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** These are internal, they may be changed without breaking the API */
const eventBus = new _events.default();
const channel = '/UserSettings/change';
/** DO NOT CHANGE. This is the localStorage key for user settings overrides */
const userSettingsLocalStorageKey = 'kui-shell/v1/user.settings';
/** Responding to a change in user settings overrides */
function on(handler) {
  eventBus.on(channel, handler);
}
/** Stop responding to a change in user settings overrides */
function off(handler) {
  eventBus.off(channel, handler);
}
/** Respond once to a change in user settings overrides */
function once(handler) {
  eventBus.once(channel, handler);
}
/** @return Any user overrides of the base KuiConfiguration */
function load() {
  return JSON.parse(localStorage.getItem(userSettingsLocalStorageKey) || '{}');
}
/** Read out one user setting */
function get(key) {
  return load()[key];
}
/** Update one user setting */
function set(key, value) {
  let val = value.toString();
  if (typeof value === 'string' && /\\u/.test(value)) {
    // e.g. \u2771 => %u2771
    // hello future citizens: if you can find a more elegant solution, please fix!
    val = unescape(value.replace(/\\u/g, '%u'));
  }
  localStorage.setItem(userSettingsLocalStorageKey, JSON.stringify(Object.assign(load(), {
    [key]: val
  })));
  eventBus.emit(channel, 'set');
}
/** Remove one user setting */
function unset(key) {
  const config = load();
  delete config[key];
  localStorage.setItem(userSettingsLocalStorageKey, JSON.stringify(config));
  eventBus.emit(channel, 'unset');
}
/** Remove all user settings */
function reset() {
  localStorage.removeItem(userSettingsLocalStorageKey);
  eventBus.emit(channel, 'reset');
}