import { LISTENERS } from '../constants';
import { serializeScene, shortcutArray } from '../helpers';
import { reactProps as props } from '../Canvas';
import _ from 'lodash';
let initiatedListeners = [];
const actionFunction = args => {
  const {
    event,
    shortcutArray
  } = args;
  const currentShortcut = shortcutArray.find(shortcut => shortcut.key === event.key);
  const isInput = event?.target.localName === 'input';
  if (!_.isEmpty(currentShortcut) && !isInput) {
    event.preventDefault();
    currentShortcut.action(event);
    props.setSerializedData?.(serializeScene());
  }
};
const shortcutListener = e => actionFunction({
  event: e,
  shortcutArray
});
export const handleShortcutListeners = remove => {
  const keyup = LISTENERS.keyup;
  if (remove) {
    if (initiatedListeners.includes(keyup)) {
      window.removeEventListener(keyup, shortcutListener);
      initiatedListeners = [];
    }
    return;
  }
  if (initiatedListeners.includes(keyup)) return;
  window.addEventListener(keyup, shortcutListener);
  initiatedListeners.push(keyup);
};