"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSearch = void 0;
const react_1 = __importDefault(require("react"));
const hooks_1 = require("../hooks");
const utility_1 = require("../utility");
const useSearch = () => {
    const { options, config, search } = (0, hooks_1.useReactifySearchContext)();
    const handleSubmitSearchQuery = react_1.default.useCallback((searchBody, searchHeaders) => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
        utility_1.debug.log("useSearch", "submitSearchQuery[body]", searchBody);
        utility_1.debug.log("useSearch", "submitSearchQuery[headers]", searchHeaders);
        const response = yield fetch(`${config.endpoint}/${config.index}/_search`, {
            method: "POST",
            body: JSON.stringify(searchBody),
            headers: searchHeaders,
        }).then((response) => {
            utility_1.debug.log("useSearch", "submitSearchQuery[status]", response.status);
            return response.json();
        }).catch((error) => {
            utility_1.debug.log("useSearch", "submitSearchQuery[error]", error);
            return error;
        });
        utility_1.debug.log("useSearch", "submitSearchQuery[response]", response);
        const value = {
            results: (_c = (_b = (_a = response.hits) === null || _a === void 0 ? void 0 : _a.hits) === null || _b === void 0 ? void 0 : _b.map((item) => item._source)) !== null && _c !== void 0 ? _c : [],
            resultStats: {
                time: (_d = response.took) !== null && _d !== void 0 ? _d : NaN,
                numberOfResults: (_g = (_f = (_e = response.hits) === null || _e === void 0 ? void 0 : _e.total) === null || _f === void 0 ? void 0 : _f.value) !== null && _g !== void 0 ? _g : NaN,
                displayedResults: (_k = (_j = (_h = response.hits) === null || _h === void 0 ? void 0 : _h.hits) === null || _j === void 0 ? void 0 : _j.length) !== null && _k !== void 0 ? _k : NaN,
            },
        };
        utility_1.debug.log("useSearch", "submitSearchQuery[value]", value);
        return value;
    }), [config.endpoint, config.index]);
    const handleSubmitSearchTerm = react_1.default.useCallback((searchTerm = search.searchTerm) => {
        utility_1.debug.log("useSearch", "submitSearchTerm[query]", searchTerm);
        if (!searchTerm) {
            return;
        }
        const redirect = config.redirects.find((redirect) => redirect.query.trim().toLowerCase() ===
            searchTerm.trim().toLowerCase());
        if (redirect) {
            utility_1.debug.log("useSearch", "submitSearchTerm[redirect]", redirect);
        }
        search.setShowInstantSearchResults(false);
        if (options.onRedirect) {
            options.onRedirect(redirect ? "redirect" : "search", redirect
                ? redirect.url
                : `/search?q=${encodeURIComponent(searchTerm)}`);
        }
        else if (redirect) {
            window.location.href = redirect.url;
        }
        else {
            window.location.href = `/search?q=${encodeURIComponent(searchTerm)}`;
        }
    }, [search.searchTerm]);
    const handleSetSearchTerm = react_1.default.useCallback((searchTerm = "") => {
        utility_1.debug.log("useSearch", "setSearchTerm[searchTerm]", searchTerm);
        search.setSearchTerm(searchTerm);
    }, [search.searchTerm]);
    return {
        searchTerm: search.searchTerm,
        setSearchTerm: handleSetSearchTerm,
        submitSearchTerm: handleSubmitSearchTerm,
        submitSearchQuery: handleSubmitSearchQuery,
        showInstantSearchResults: !!search.showInstantSearchResults && !!search.searchTerm,
        setShowInstantSearchResults: search.setShowInstantSearchResults,
        searchRedirect: search.searchRedirect,
    };
};
exports.useSearch = useSearch;
//# sourceMappingURL=useSearch.js.map