export function keyboardListener(responseMap) {
  return [document.body, 'keydown', keyResponder(responseMap), {passive: false}];
}

export const KEY_CODES = {
  backspace: 8,
  up: 38,
  down: 40,
  left: 37,
  right: 39,
  enter: 13,
  esc: 27,
  space: 32,
  f: 70
};

function keyResponder(responseMap) {
  return function (e) {
    if (e.keyCode === KEY_CODES.backspace) {
      tryCall(this, responseMap.back, e);
    } else if (e.keyCode === KEY_CODES.down) {
      tryCall(this, responseMap.down, e);
    } else if (e.keyCode === KEY_CODES.enter) {
      tryCall(this, responseMap.enter, e);
    } else if (e.keyCode === KEY_CODES.esc) {
      tryCall(this, responseMap.esc, e);
    } else if (e.altKey && e.keyCode === KEY_CODES.f) {
      tryCall(this, responseMap.find, e);
    } else if (e.keyCode === KEY_CODES.up) {
      tryCall(this, responseMap.up, e);
    } else if (e.keyCode === KEY_CODES.left) {
      tryCall(this, responseMap.left, e);
    } else if (e.keyCode === KEY_CODES.right) {
      tryCall(this, responseMap.right, e);
    }
  };
}

function tryCall(context, fn, e) {
  if (!fn) {
    return;
  }

  fn.call(context, e);
}
