import { _ as __assign, a as __spreadArray } from './bundle-B8Grfnrx.js';
import { u as useStore, c as createStore, s as shimExports } from './bundle-C4OmfIXk.js';
import React__default, { useEffect, useCallback, useState, createContext, useRef, useMemo, useContext } from 'react';
import { u as useSendbird } from './bundle-I25ah_Bv.js';

function useSetChannel(_a, _b) {
    var channelUrl = _a.channelUrl, sdkInit = _a.sdkInit;
    var sdk = _b.sdk, logger = _b.logger;
    var _c = useMessageSearch().actions, setCurrentChannel = _c.setCurrentChannel, setChannelInvalid = _c.setChannelInvalid;
    useEffect(function () {
        if (channelUrl && sdkInit && (sdk === null || sdk === void 0 ? void 0 : sdk.groupChannel)) {
            sdk.groupChannel.getChannel(channelUrl)
                .then(function (groupChannel) {
                logger.info('MessageSearch | useSetChannel group channel', groupChannel);
                setCurrentChannel(groupChannel);
            })
                .catch(function () {
                setChannelInvalid();
            });
        }
    }, [channelUrl, sdkInit]);
}

var MessageSearchOrder;
(function (MessageSearchOrder) {
    MessageSearchOrder["SCORE"] = "score";
    MessageSearchOrder["TIMESTAMP"] = "ts";
})(MessageSearchOrder || (MessageSearchOrder = {}));
function useGetSearchedMessages(_a, _b) {
    var currentChannel = _a.currentChannel, channelUrl = _a.channelUrl, requestString = _a.requestString, messageSearchQuery = _a.messageSearchQuery, onResultLoaded = _a.onResultLoaded;
    var sdk = _b.sdk, logger = _b.logger;
    var _c = useMessageSearch(), retryCount = _c.state.retryCount, _d = _c.actions, startMessageSearch = _d.startMessageSearch, getSearchedMessages = _d.getSearchedMessages, setQueryInvalid = _d.setQueryInvalid, startGettingSearchedMessages = _d.startGettingSearchedMessages;
    var handleSearchError = useCallback(function (error) {
        logger.warning('MessageSearch | useGetSearchedMessages: failed getting search messages.', error);
        setQueryInvalid();
        if (onResultLoaded && typeof onResultLoaded === 'function') {
            onResultLoaded(undefined, error);
        }
    }, [logger, setQueryInvalid, onResultLoaded]);
    useEffect(function () {
        startMessageSearch();
        if (sdk && channelUrl && sdk.createMessageSearchQuery && currentChannel && requestString) {
            currentChannel.refresh()
                .then(function (channel) {
                var inputSearchMessageQueryObject = __assign({ order: MessageSearchOrder.TIMESTAMP, channelUrl: channelUrl, messageTimestampFrom: channel.invitedAt, keyword: requestString }, messageSearchQuery);
                var createdQuery = sdk.createMessageSearchQuery(inputSearchMessageQueryObject);
                startGettingSearchedMessages(createdQuery);
                createdQuery.next().then(function (messages) {
                    logger.info('MessageSearch | useGetSearchedMessages: succeeded getting messages', messages);
                    getSearchedMessages(messages, createdQuery);
                    if (onResultLoaded && typeof onResultLoaded === 'function') {
                        onResultLoaded(messages, undefined);
                    }
                }).catch(handleSearchError);
            })
                .catch(function (error) {
                logger.warning('MessageSearch | useGetSearchedMessages: failed getting channel.', error);
                handleSearchError(error);
            });
        }
        else if (!requestString) {
            logger.info('MessageSearch | useGetSearchedMessages: search string is empty');
        }
    }, [channelUrl, messageSearchQuery, requestString, currentChannel, retryCount]);
}

function useScrollCallback(_a, _b) {
    var onResultLoaded = _a.onResultLoaded;
    var logger = _b.logger;
    var _c = useMessageSearch(), _d = _c.state, currentMessageSearchQuery = _d.currentMessageSearchQuery, hasMoreResult = _d.hasMoreResult, getNextSearchedMessages = _c.actions.getNextSearchedMessages;
    return useCallback(function (cb) {
        if (!hasMoreResult) {
            logger.warning('MessageSearch | useScrollCallback: no more searched results', hasMoreResult);
        }
        if (currentMessageSearchQuery && currentMessageSearchQuery.hasNext) {
            currentMessageSearchQuery
                .next()
                .then(function (messages) {
                logger.info('MessageSearch | useScrollCallback: succeeded getting searched messages', messages);
                getNextSearchedMessages(messages);
                cb(messages, null);
                if (onResultLoaded && typeof onResultLoaded === 'function') {
                    onResultLoaded(messages, null);
                }
            })
                .catch(function (error) {
                logger.warning('MessageSearch | useScrollCallback: failed getting searched messages', error);
                cb(null, error);
                if (onResultLoaded && typeof onResultLoaded === 'function') {
                    onResultLoaded(null, error);
                }
            });
        }
        else {
            logger.warning('MessageSearch | useScrollCallback: no currentMessageSearchQuery');
        }
    }, [currentMessageSearchQuery, hasMoreResult]);
}

var DEBOUNCING_TIME = 500;
function useSearchStringEffect(_a) {
    var searchString = _a.searchString;
    var _b = useState(''), requestString = _b[0], setRequestString = _b[1];
    var _c = useState(null), debouncingTimer = _c[0], setDebouncingTimer = _c[1];
    var resetSearchString = useMessageSearch().actions.resetSearchString;
    var handleSearchStringChange = useCallback(function () {
        if (searchString) {
            setRequestString(searchString);
        }
        else {
            setRequestString('');
            resetSearchString();
        }
    }, [searchString, resetSearchString]);
    useEffect(function () {
        if (debouncingTimer) {
            clearTimeout(debouncingTimer);
        }
        var timer = setTimeout(handleSearchStringChange, DEBOUNCING_TIME);
        setDebouncingTimer(timer);
        return function () {
            if (timer) {
                clearTimeout(timer);
            }
        };
    }, [searchString, handleSearchStringChange]);
    return requestString;
}

var initialState = {
    channelUrl: '',
    allMessages: [],
    loading: false,
    isInvalid: false,
    initialized: false,
    currentChannel: null,
    currentMessageSearchQuery: null,
    messageSearchQuery: null,
    hasMoreResult: false,
    retryCount: 0,
    selectedMessageId: null,
    searchString: '',
    requestString: '',
    /**
     * messageSearchDispatcher is no longer used.
     * Please use useMessageSearch() to get the store and update the state.
     */
    // messageSearchDispatcher: null,
};
var MessageSearchContext = createContext(null);
var MessageSearchManager = function (_a) {
    var _b, _c;
    var channelUrl = _a.channelUrl, searchString = _a.searchString, messageSearchQuery = _a.messageSearchQuery, onResultLoaded = _a.onResultLoaded, onResultClick = _a.onResultClick;
    var _d = useMessageSearchStore(), state = _d.state, updateState = _d.updateState;
    var _e = useSendbird().state, config = _e.config, stores = _e.stores;
    var sdk = (_b = stores === null || stores === void 0 ? void 0 : stores.sdkStore) === null || _b === void 0 ? void 0 : _b.sdk;
    var sdkInit = (_c = stores === null || stores === void 0 ? void 0 : stores.sdkStore) === null || _c === void 0 ? void 0 : _c.initialized;
    var logger = config.logger;
    var scrollRef = useRef(null);
    useSetChannel({ channelUrl: channelUrl, sdkInit: sdkInit }, { sdk: sdk, logger: logger });
    var _searchString = useMemo(function () {
        var _a;
        return (_a = searchString !== null && searchString !== void 0 ? searchString : messageSearchQuery === null || messageSearchQuery === void 0 ? void 0 : messageSearchQuery.keyword) !== null && _a !== void 0 ? _a : '';
    }, [searchString, messageSearchQuery === null || messageSearchQuery === void 0 ? void 0 : messageSearchQuery.keyword]);
    var requestString = useSearchStringEffect({ searchString: _searchString });
    useGetSearchedMessages({
        currentChannel: state.currentChannel,
        channelUrl: channelUrl,
        requestString: requestString,
        messageSearchQuery: messageSearchQuery,
        onResultLoaded: onResultLoaded,
    }, { sdk: sdk, logger: logger });
    var onScroll = useScrollCallback({ onResultLoaded: onResultLoaded }, { logger: logger });
    var handleOnScroll = useCallback(function (e) {
        var scrollElement = e.target;
        var scrollTop = scrollElement.scrollTop, scrollHeight = scrollElement.scrollHeight, clientHeight = scrollElement.clientHeight;
        if (!state.hasMoreResult) {
            return;
        }
        if (scrollTop + clientHeight >= scrollHeight) {
            onScroll(function () {
                // after load more searched messages
            });
        }
    }, [state.hasMoreResult, onScroll]);
    useEffect(function () {
        updateState({
            channelUrl: channelUrl,
            searchString: _searchString,
            messageSearchQuery: messageSearchQuery,
            onResultClick: onResultClick,
            onScroll: onScroll,
            handleOnScroll: handleOnScroll,
            scrollRef: scrollRef,
            requestString: requestString,
        });
    }, [channelUrl, searchString, messageSearchQuery, onResultClick, updateState, requestString]);
    return null;
};
var createMessageSearchStore = function () { return createStore(initialState); };
var InternalMessageSearchProvider = function (_a) {
    var children = _a.children;
    var storeRef = useRef(createMessageSearchStore());
    return (React__default.createElement(MessageSearchContext.Provider, { value: storeRef.current }, children));
};
var MessageSearchProvider = function (_a) {
    var children = _a.children, channelUrl = _a.channelUrl, searchString = _a.searchString, messageSearchQuery = _a.messageSearchQuery, onResultLoaded = _a.onResultLoaded, onResultClick = _a.onResultClick;
    return (React__default.createElement(InternalMessageSearchProvider, null,
        React__default.createElement(MessageSearchManager, { channelUrl: channelUrl, searchString: searchString, messageSearchQuery: messageSearchQuery, onResultLoaded: onResultLoaded, onResultClick: onResultClick }),
        children));
};
// Keep this function for backward compatibility.
var useMessageSearchContext = function () {
    var _a = useMessageSearch(), state = _a.state, actions = _a.actions;
    return __assign(__assign({}, state), actions);
};
/**
 * A specialized hook for MessageSearch state management
 * @returns {ReturnType<typeof createStore<MessageSearchState>>}
 */
var useMessageSearchStore = function () {
    return useStore(MessageSearchContext, function (state) { return state; }, initialState);
};

var useMessageSearch = function () {
    var store = useContext(MessageSearchContext);
    if (!store)
        throw new Error('useMessageSearch must be used within a MessageSearchProvider');
    var state = shimExports.useSyncExternalStore(store.subscribe, store.getState);
    var actions = useMemo(function () { return ({
        setCurrentChannel: function (channel) { return store.setState(function (state) { return (__assign(__assign({}, state), { currentChannel: channel, initialized: true })); }); },
        setChannelInvalid: function () { return store.setState(function (state) { return (__assign(__assign({}, state), { currentChannel: null, initialized: false })); }); },
        getSearchedMessages: function (messages, createdQuery) {
            store.setState(function (state) {
                var _a;
                if (createdQuery && createdQuery.channelUrl === ((_a = state.currentMessageSearchQuery) === null || _a === void 0 ? void 0 : _a.channelUrl)
                    && createdQuery.key === state.currentMessageSearchQuery.key) {
                    return __assign(__assign({}, state), { loading: false, isInvalid: false, allMessages: messages, hasMoreResult: state.currentMessageSearchQuery.hasNext });
                }
                return state;
            });
        },
        setQueryInvalid: function () { return store.setState(function (state) { return (__assign(__assign({}, state), { isInvalid: true })); }); },
        startMessageSearch: function () { return store.setState(function (state) { return (__assign(__assign({}, state), { isInvalid: false, loading: false })); }); },
        startGettingSearchedMessages: function (query) { return store.setState(function (state) { return (__assign(__assign({}, state), { loading: true, currentMessageSearchQuery: query })); }); },
        getNextSearchedMessages: function (messages) { return store.setState(function (state) {
            var _a;
            return (__assign(__assign({}, state), { allMessages: __spreadArray(__spreadArray([], state.allMessages, true), messages, true), hasMoreResult: ((_a = state.currentMessageSearchQuery) === null || _a === void 0 ? void 0 : _a.hasNext) || false }));
        }); },
        resetSearchString: function () { return store.setState(function (state) { return (__assign(__assign({}, state), { allMessages: [] })); }); },
        setSelectedMessageId: function (messageId) { return store.setState(function (state) { return (__assign(__assign({}, state), { selectedMessageId: messageId })); }); },
        handleRetryToConnect: function () { return store.setState(function (state) { return (__assign(__assign({}, state), { retryCount: state.retryCount + 1 })); }); },
        // Looks exactly same as handleRetryToConnect but keep just for backward compatibility
        setRetryCount: function () { return store.setState(function (state) { return (__assign(__assign({}, state), { retryCount: state.retryCount + 1 })); }); },
    }); }, [store]);
    return { state: state, actions: actions };
};

export { MessageSearchContext as M, MessageSearchProvider as a, useMessageSearchContext as b, MessageSearchManager as c, useMessageSearch as u };
//# sourceMappingURL=bundle-CinANGYQ.js.map
