(function (global) {
  global.ARQ = global.ARQ || {};

  function activeSheet() {
    return ARQ.utils.activeSheet(ARQ.store.getProject());
  }

  function setToolFromKeys(t) {
    if (ARQ.tools && ARQ.tools.setTool) ARQ.tools.setTool(t);
  }

  ARQ.keyboard = {
    init: function () {
      global.addEventListener('keydown', function (e) {
        var tag = (e.target && e.target.tagName) || '';
        var inField = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable);

        if (!inField) {
          if (e.key === 'Escape') {
            if (ARQ.transform && ARQ.transform.isActive && ARQ.transform.isActive()) {
              ARQ.transform.deactivate();
            }
            var shEsc = activeSheet();
            if (ARQ.selection && shEsc) {
              ARQ.selection.clear(shEsc);
            }
            if (ARQ.canvasEngine && ARQ.canvasEngine.redraw) ARQ.canvasEngine.redraw();
            e.preventDefault();
            return;
          }
          if ((e.ctrlKey || e.metaKey) && (e.key === 't' || e.key === 'T')) {
            if (ARQ.transform && ARQ.transform.toggleForActiveLayer) {
              e.preventDefault();
              ARQ.transform.toggleForActiveLayer();
            }
            return;
          }
          if ((e.ctrlKey || e.metaKey) && (e.key === 'j' || e.key === 'J')) {
            if (ARQ.layers && ARQ.layers.duplicateActiveLayer) {
              e.preventDefault();
              ARQ.layers.duplicateActiveLayer();
            }
            return;
          }
          if (e.key === 'Enter' && ARQ.tools && ARQ.tools.currentTool() === 'crop') {
            var shC = activeSheet();
            if (shC && ARQ.selection && ARQ.selection.getCropDraft) {
              var cd = ARQ.selection.getCropDraft(shC);
              if (cd && ARQ.sheets && ARQ.sheets.applyCropRect) {
                var x0 = Math.min(cd.x0, cd.x1);
                var y0 = Math.min(cd.y0, cd.y1);
                var rw = Math.abs(cd.x1 - cd.x0);
                var rh = Math.abs(cd.y1 - cd.y0);
                if (rw >= 1 && rh >= 1) {
                  e.preventDefault();
                  ARQ.sheets.applyCropRect(shC, x0, y0, rw, rh);
                }
              }
            }
            return;
          }
          if (!e.ctrlKey && !e.metaKey && !e.altKey) {
            if (e.key === 'm' || e.key === 'M') {
              setToolFromKeys('marquee');
              e.preventDefault();
              return;
            }
            if (e.key === 'l' || e.key === 'L') {
              setToolFromKeys('lasso');
              e.preventDefault();
              return;
            }
            if (e.key === 'w' || e.key === 'W') {
              setToolFromKeys('wand');
              e.preventDefault();
              return;
            }
            if (e.key === 'v' || e.key === 'V') {
              setToolFromKeys('mover');
              e.preventDefault();
              return;
            }
            if (e.key === 'c' || e.key === 'C') {
              setToolFromKeys('crop');
              e.preventDefault();
              return;
            }
            if (e.key === 'g' || e.key === 'G') {
              setToolFromKeys('bote_pintura');
              e.preventDefault();
              return;
            }
            if (e.key === 'b' || e.key === 'B') {
              setToolFromKeys('pincel_suave');
              e.preventDefault();
              return;
            }
          }
          if (e.key === 'Delete' || e.key === 'Backspace') {
            var shD = activeSheet();
            if (ARQ.selection && shD && ARQ.selection.hasMask(shD)) {
              var lyrD = ARQ.store.activeLayer();
              if (lyrD) {
                ARQ.history.pushUndo();
                ARQ.selection.eraseMaskedPixels(shD, lyrD).then(function (ok) {
                  if (ok && ARQ.history.pushDescription) ARQ.history.pushDescription('Borrar selección');
                  if (!ok && ARQ.history.undo) ARQ.history.undo();
                  if (ARQ.layers && ARQ.layers.renderPanel) ARQ.layers.renderPanel();
                  if (ARQ.actionLog && ARQ.actionLog.append) {
                    ARQ.actionLog.append(shD, 'erase_selection', lyrD.id, {});
                  }
                });
              }
              e.preventDefault();
              return;
            }
            if (e.key === 'Delete' && ARQ.layers && ARQ.layers.removeActiveLayer) {
              ARQ.layers.removeActiveLayer();
              e.preventDefault();
            }
            return;
          }
        }

        if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
          if (inField) return;
          e.preventDefault();
          if (ARQ.history && ARQ.history.undo) ARQ.history.undo();
          return;
        }
        if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.key === 'z' && e.shiftKey))) {
          if (inField) return;
          e.preventDefault();
          if (ARQ.history && ARQ.history.redo) ARQ.history.redo();
        }
      });
    },
  };
})(typeof window !== 'undefined' ? window : this);
