import { consoleWarning } from "../../../utils/helpers/consoleWarning.js";
import { useControllableState, useEventCallback } from "../../../utils/hooks/index.js";
function useTableSort(options) {
    const { defaultSortOrder, onSortOrderChange, sortOrder, allowMultiSort = true, } = options || {};
    const [sort, setSort] = useControllableState({
        value: sortOrder,
        defaultValue: defaultSortOrder || [],
    });
    const handleSortClick = useEventCallback((id, event) => {
        if (id === undefined) {
            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" },
    };
}
export { useTableSort };
//# sourceMappingURL=useTableSort.js.map