/* -------------------------------------------------------------------------- */
/*                                  Libraries                                 */
/* -------------------------------------------------------------------------- */
import React from "react";
import { HotKeys, KeyMap } from "react-hotkeys";
import { useUIViewModel } from "ui/controller/uiViewModel";
import { useUIStore } from "ui/data/uiSlice";

type Props = {
  children: React.ReactNode;
};
/* -------------------------------------------------------------------------- */
/*                                 Definitions                                */
/* -------------------------------------------------------------------------- */
/* ------------------------------ Hot keys map ------------------------------ */
const keyMap = {
  SEARCHBAR_OPEN: "ctrl+k",
};
function _getHotKeys(): KeyMap {
  return keyMap;
}
/* ---------------------------- Hot keys handlers --------------------------- */
type HotKeyHandlers = {
  [Property in keyof typeof keyMap]: (event: KeyboardEvent | undefined) => void;
};
/* -------------------------------------------------------------------------- */
/*                        Application hot keys handler                        */
/* -------------------------------------------------------------------------- */
export default function AppHotKeys({ children }: Props) {
  const store = useUIStore();
  const { isSearchbarShown, showSearchbar } = useUIViewModel(store);

  const getAppHotKeys = React.useCallback(_getHotKeys, []);
  const getAppHotKeyHandlers = React.useCallback(
    (): HotKeyHandlers => ({
      SEARCHBAR_OPEN: (event) => {
        event?.preventDefault();
        if (isSearchbarShown) return;
        showSearchbar();
      },
    }),
    [isSearchbarShown, showSearchbar]
  );
  return (
    <HotKeys keyMap={getAppHotKeys()} handlers={getAppHotKeyHandlers()}>
      {children}
    </HotKeys>
  );
}
