import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import React, { createContext, useContext, useMemo } from "react";
import { defaultHotkeys } from "./default-hotkeys";
import { useAppConfig } from "../AppConfig";
export var HotkeyContext = createContext({
  hotkeys: defaultHotkeys,
  changeHotkey: function changeHotkey(id, newBinding) {
    return null;
  }
});
export var useHotkeyStorage = function useHotkeyStorage() {
  return useContext(HotkeyContext);
};
export var HotkeyStorageProvider = function HotkeyStorageProvider(_ref) {
  var children = _ref.children;

  var _useAppConfig = useAppConfig(),
      fromConfig = _useAppConfig.fromConfig,
      setInConfig = _useAppConfig.setInConfig,
      clearInConfig = _useAppConfig.clearInConfig;

  var hotkeys = useMemo(function () {
    return defaultHotkeys.map(function (item) {
      if (fromConfig("hotkeys.".concat(item.id))) {
        return _objectSpread(_objectSpread({}, item), {}, {
          binding: fromConfig("hotkeys.".concat(item.id))
        });
      } else {
        return item;
      }
    });
  }, [fromConfig]);
  var keyMap = useMemo(function () {
    var keyMap = {};

    var _iterator = _createForOfIteratorHelper(hotkeys),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _step$value = _step.value,
            id = _step$value.id,
            binding = _step$value.binding;
        if (!binding) continue;
        keyMap[id] = binding;
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return keyMap;
  }, [hotkeys]);
  var contextValue = useMemo(function () {
    return {
      hotkeys: hotkeys,
      keyMap: keyMap,
      clearHotkeys: function clearHotkeys() {
        clearInConfig(hotkeys.map(function (key) {
          return "hotkeys.".concat(key.id);
        }));
      },
      changeHotkey: function changeHotkey(id, newBinding) {
        return setInConfig("hotkeys.".concat(id), newBinding);
      }
    };
  }, [hotkeys, keyMap, clearInConfig, setInConfig]);
  return /*#__PURE__*/React.createElement(HotkeyContext.Provider, {
    value: contextValue
  }, children);
};
export { defaultHotkeys };