"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.beforeKeyDownHandler = void 0;
function beforeKeyDownHandler(grid) {
    return function (e) {
        var table = this;
        var payload = toKeydownPayload(e, grid);
        var cancel = payload.cancel, key = payload.key;
        grid.fire({ type: 'GRID/keydown', payload: payload });
        if (grid.isEditing) {
            e.stopImmediatePropagation();
        }
        var last = table.getSelectedLast();
        if (last && !grid.isEditing) {
            var row = last[0];
            var column = last[1];
            if (key === 'ArrowUp' && row === 0) {
                cancel();
            }
            if (key === 'ArrowLeft' && column === 0) {
                cancel();
            }
            if (key === 'ArrowDown' && row === grid.totalRows - 1) {
                cancel();
            }
            if (key === 'ArrowRight' && column === grid.totalColumns - 1) {
                cancel();
            }
            if (key === 'Backspace' || key === 'Delete') {
                handleDelete({ grid: grid, keydown: payload });
            }
        }
    };
}
exports.beforeKeyDownHandler = beforeKeyDownHandler;
function toKeydownPayload(e, grid) {
    var event = e;
    var key = event.key;
    var isEnter = key === 'Enter';
    var isEscape = key === 'Escape';
    var isDelete = key === 'Delete';
    var metaKey = event.metaKey, shiftKey = event.shiftKey, ctrlKey = event.ctrlKey, altKey = event.altKey;
    var payload = {
        key: key,
        grid: grid,
        event: event,
        isEnter: isEnter,
        isEscape: isEscape,
        isDelete: isDelete,
        metaKey: metaKey,
        shiftKey: shiftKey,
        ctrlKey: ctrlKey,
        altKey: altKey,
        isCancelled: false,
        cancel: function () {
            e.preventDefault();
            e.stopImmediatePropagation();
            payload.isCancelled = true;
        },
    };
    return payload;
}
function handleDelete(args) {
    var grid = args.grid, keydown = args.keydown;
    keydown.cancel();
    var deleted = {};
    Object.keys(grid.selectionValues).forEach(function (key) { return (deleted[key] = undefined); });
    grid.changeCells(deleted, { source: 'DELETE' });
}
