"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSortBy = void 0;
const react_1 = __importDefault(require("react"));
const hooks_1 = require("../hooks");
const utility_1 = require("../utility");
const sortOption_1 = require("../utility/sortOption");
const useSortBy = () => {
    const reactifySearchContext = (0, hooks_1.useReactifySearchContext)();
    const { track } = (0, hooks_1.useAnalytics)();
    const sortOptions = react_1.default.useMemo(() => {
        return (0, sortOption_1.getSortOptions)({
            provider: reactifySearchContext.options,
            config: reactifySearchContext.config,
        });
    }, [reactifySearchContext.options, reactifySearchContext.config]);
    const sortOption = react_1.default.useMemo(() => {
        return (0, sortOption_1.getSortOption)({
            provider: reactifySearchContext.options,
            config: reactifySearchContext.config,
            sortOption: reactifySearchContext.sortby.sortOption,
        });
    }, [reactifySearchContext.options, reactifySearchContext.config, reactifySearchContext.sortby.sortOption]);
    const setSortOption = react_1.default.useCallback((sortOptionHandle, ignoreHistoryState = false) => {
        if (typeof window === "undefined") {
            return;
        }
        utility_1.debug.log("useSortBy", "setSortOption[sortOptionHandle]", sortOptionHandle);
        reactifySearchContext.sortby.setSortOption(sortOptionHandle);
        if (!ignoreHistoryState) {
            const url = new URL(window.location.href);
            if (url.searchParams.has("sort")) {
                url.searchParams.set("sort", sortOptionHandle);
            }
            else {
                url.searchParams.append("sort", sortOptionHandle);
            }
            window.history.pushState({}, "", url.toString());
        }
        track({
            eventName: "sortChange",
            payload: {
                type: sortOptionHandle,
            },
        });
    }, [typeof window === "undefined" ? "" : window.location.href]);
    return {
        sortOptions,
        sortOption,
        setSortOption,
    };
};
exports.useSortBy = useSortBy;
//# sourceMappingURL=useSortBy.js.map