"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SensorSearchTerm = void 0;
const react_1 = __importDefault(require("react"));
const ahooks_1 = require("ahooks");
const DataSearch_1 = __importDefault(require("@usereactify/search-internals/lib/components/search/DataSearch"));
const hooks_1 = require("../../hooks");
const SensorSearchTerm = () => {
    const flagsHook = (0, hooks_1.useFlags)();
    const { options, config } = (0, hooks_1.useReactifySearchContext)();
    const { track } = (0, hooks_1.useAnalytics)();
    const { searchTerm } = (0, hooks_1.useSearch)();
    const [searchTermDebounced, setSearchTermDebounced] = react_1.default.useState(searchTerm);
    // ignore search fields only set for instant search
    const searchFields = react_1.default.useMemo(() => {
        if (options.mode === "search") {
            return config.fields.filter((field) => ["always_search", "search_page"].includes(field.searchType));
        }
        if (options.mode === "instant-search") {
            return config.fields.filter((field) => ["always_search", "instant_search"].includes(field.searchType));
        }
        return [];
    }, [config.fields]);
    const { run: runDebouncedTriggerQuery, cancel: cancelDebouncedTriggerQuery } = (0, ahooks_1.useDebounceFn)((value) => {
        setSearchTermDebounced(value);
        let trimmedSearchTerm = searchTerm.trim();
        if (!trimmedSearchTerm ||
            (trimmedSearchTerm && trimmedSearchTerm.length < 3)) {
            return;
        }
        track({
            eventName: "search",
            payload: {
                searchTerm: trimmedSearchTerm,
            },
        });
    }, {
        wait: 300,
    });
    react_1.default.useEffect(() => {
        runDebouncedTriggerQuery(searchTerm);
    }, [searchTerm]);
    if (searchFields.length === 0) {
        return null;
    }
    if (!flagsHook.flags["reactify-search:flag_sensor_searchterm"]) {
        return null;
    }
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(DataSearch_1.default, { fuzziness: 1, queryFormat: "and", autosuggest: false, value: searchTermDebounced, componentId: "SensorSearchTerm", style: { display: "none" }, dataField: searchFields.map((field) => field.field), fieldWeights: searchFields.map((field) => field.importance), customQuery: (value, props) => {
                const valueNormal = value.toLowerCase().trim();
                const conditions = [];
                if (flagsHook.flags["reactify-search:flag_sensor_searchterm_value"] &&
                    valueNormal) {
                    if (options.market) {
                        conditions.push({
                            nested: {
                                path: "curations",
                                query: {
                                    bool: {
                                        must: [
                                            {
                                                term: {
                                                    "curations.searchTerm.keyword": valueNormal,
                                                },
                                            },
                                            {
                                                term: {
                                                    "curations.markets.keyword": options.market,
                                                },
                                            },
                                        ],
                                    },
                                },
                            },
                        });
                    }
                    else {
                        conditions.push({
                            nested: {
                                path: "curations",
                                query: {
                                    term: {
                                        "curations.searchTerm.keyword": valueNormal,
                                    },
                                },
                            },
                        });
                    }
                }
                const fieldsPhrase = props.dataField
                    .filter((field) => !flagsHook.flags["reactify-search:flag_sensor_searchterm_phrase_synonyms"]
                    ? !field.includes("synonym")
                    : true)
                    .map((field, index) => `${field}^${props.fieldWeights[index]}`);
                if (flagsHook.flags["reactify-search:flag_sensor_searchterm_phrase"] &&
                    fieldsPhrase.length > 0) {
                    conditions.push({
                        multi_match: {
                            query: valueNormal,
                            fields: fieldsPhrase,
                            type: "phrase",
                            operator: "and",
                        },
                    });
                }
                const fieldsPhrasePrefix = props.dataField
                    .filter((field) => !flagsHook.flags["reactify-search:flag_sensor_searchterm_phrase_prefix_synonyms"]
                    ? !field.includes("synonym")
                    : true)
                    .map((field, index) => `${field}^${props.fieldWeights[index]}`)
                    .filter((field) => !field.includes("."));
                if (flagsHook.flags["reactify-search:flag_sensor_searchterm_phrase_prefix"] &&
                    fieldsPhrasePrefix.length > 0) {
                    conditions.push({
                        multi_match: {
                            query: valueNormal,
                            fields: fieldsPhrasePrefix,
                            type: "phrase_prefix",
                            operator: "and",
                        },
                    });
                }
                const fieldsCrossFields = props.dataField
                    .filter((field) => !flagsHook.flags["reactify-search:flag_sensor_searchterm_cross_fields_synonyms"]
                    ? !field.includes("synonym")
                    : true)
                    .map((field, index) => `${field}^${props.fieldWeights[index]}`);
                if (flagsHook.flags["reactify-search:flag_sensor_searchterm_cross_fields"] &&
                    fieldsCrossFields.length > 0) {
                    conditions.push({
                        multi_match: {
                            query: valueNormal,
                            fields: fieldsCrossFields,
                            type: "cross_fields",
                            operator: "and",
                        },
                    });
                }
                const fieldsSpanFirst = props.dataField
                    .filter((field) => !flagsHook.flags["reactify-search:flag_sensor_searchterm_span_first_synonyms"]
                    ? !field.includes("synonym")
                    : true)
                    .filter((field) => {
                    if (field.endsWith(".keyword")) {
                        return false;
                    }
                    return true;
                })
                    .map((field) => ({
                    span_first: {
                        match: {
                            span_term: { [`${field}`]: valueNormal },
                        },
                        end: 1,
                    },
                }));
                if (flagsHook.flags["reactify-search:flag_sensor_searchterm_span_first"] &&
                    fieldsSpanFirst.length > 0) {
                    conditions.push(...fieldsSpanFirst);
                }
                return {
                    query: {
                        bool: {
                            should: conditions,
                            minimum_should_match: "1",
                        },
                    },
                };
            } })));
};
exports.SensorSearchTerm = SensorSearchTerm;
//# sourceMappingURL=SensorSearchTerm.js.map