"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTableSort = useTableSort;
const consoleWarning_1 = require("../../../utils/helpers/consoleWarning");
const hooks_1 = require("../../../utils/hooks");
function useTableSort(options) {
    const { defaultSortOrder, onSortOrderChange, sortOrder, allowMultiSort = true, } = options || {};
    const [sort, setSort] = (0, hooks_1.useControllableState)({
        value: sortOrder,
        defaultValue: defaultSortOrder || [],
    });
    const handleSortClick = (0, hooks_1.useEventCallback)((id, event) => {
        if (id === undefined) {
            (0, consoleWarning_1.consoleWarning)("DataGrid.Table: Column id is undefined for sort event on target", event.target, "Make sure your column definitions include an 'id' property.");
            return;
        }
        const cumulative = allowMultiSort && event.shiftKey;
        const base = cumulative ? sort : sort.filter((s) => s.columnId === id);
        const { next, detail } = nextSortEntries(base, id);
        setSort(next);
        onSortOrderChange === null || onSortOrderChange === void 0 ? void 0 : onSortOrderChange(next, detail);
    });
    return {
        onSortClick: handleSortClick,
        sortState: sort,
    };
}
function nextSortEntries(current, columnId) {
    const existing = current.find((s) => s.columnId === columnId);
    if (!existing) {
        return {
            next: [...current, { columnId, direction: "asc" }],
            detail: { columnId, direction: "asc" },
        };
    }
    if (existing.direction === "asc") {
        return {
            next: current.map((s) => s.columnId === columnId ? Object.assign(Object.assign({}, s), { direction: "desc" }) : s),
            detail: { columnId, direction: "desc" },
        };
    }
    return {
        next: current.filter((s) => s.columnId !== columnId),
        detail: { columnId, direction: "none" },
    };
}
//# sourceMappingURL=useTableSort.js.map