'use strict';

var _tslib = require('./bundle-Conb-pOy.js');
var SendbirdContext = require('./bundle-B19RHFpR.js');
var React = require('react');
var useSendbird = require('./bundle-Bq15P9qk.js');
var utils = require('./bundle-CkQrhwR6.js');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefaultCompat(React);

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;
    React.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 = React.useCallback(function (error) {
        logger.warning('MessageSearch | useGetSearchedMessages: failed getting search messages.', error);
        setQueryInvalid();
        if (onResultLoaded && typeof onResultLoaded === 'function') {
            onResultLoaded(undefined, error);
        }
    }, [logger, setQueryInvalid, onResultLoaded]);
    React.useEffect(function () {
        startMessageSearch();
        if (sdk && channelUrl && sdk.createMessageSearchQuery && currentChannel && requestString) {
            currentChannel.refresh()
                .then(function (channel) {
                var inputSearchMessageQueryObject = _tslib.__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 React.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 = React.useState(''), requestString = _b[0], setRequestString = _b[1];
    var _c = React.useState(null), debouncingTimer = _c[0], setDebouncingTimer = _c[1];
    var resetSearchString = useMessageSearch().actions.resetSearchString;
    var handleSearchStringChange = React.useCallback(function () {
        if (searchString) {
            setRequestString(searchString);
        }
        else {
            setRequestString('');
            resetSearchString();
        }
    }, [searchString, resetSearchString]);
    React.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 = React.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.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 = React.useRef(null);
    useSetChannel({ channelUrl: channelUrl, sdkInit: sdkInit }, { sdk: sdk, logger: logger });
    var _searchString = React.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 = React.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]);
    React.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 (props) { return SendbirdContext.createStore(_tslib.__assign(_tslib.__assign({}, initialState), props)); };
var InternalMessageSearchProvider = function (props) {
    var children = props.children;
    var defaultProps = utils.deleteNullish({
        channelUrl: props === null || props === void 0 ? void 0 : props.channelUrl,
        messageSearchQuery: props === null || props === void 0 ? void 0 : props.messageSearchQuery,
        searchString: props === null || props === void 0 ? void 0 : props.searchString,
        onResultLoaded: props === null || props === void 0 ? void 0 : props.onResultLoaded,
        onResultClick: props === null || props === void 0 ? void 0 : props.onResultClick,
    });
    var storeRef = React.useRef(createMessageSearchStore(defaultProps));
    return (React__default.default.createElement(MessageSearchContext.Provider, { value: storeRef.current }, children));
};
var MessageSearchProvider = function (props) {
    var children = props.children, channelUrl = props.channelUrl, searchString = props.searchString, messageSearchQuery = props.messageSearchQuery, onResultLoaded = props.onResultLoaded, onResultClick = props.onResultClick;
    return (React__default.default.createElement(InternalMessageSearchProvider, _tslib.__assign({}, props),
        React__default.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 _tslib.__assign(_tslib.__assign({}, state), actions);
};
/**
 * A specialized hook for MessageSearch state management
 * @returns {ReturnType<typeof createStore<MessageSearchState>>}
 */
var useMessageSearchStore = function () {
    return SendbirdContext.useStore(MessageSearchContext, function (state) { return state; }, initialState);
};

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

exports.MessageSearchContext = MessageSearchContext;
exports.MessageSearchManager = MessageSearchManager;
exports.MessageSearchProvider = MessageSearchProvider;
exports.useMessageSearch = useMessageSearch;
exports.useMessageSearchContext = useMessageSearchContext;
//# sourceMappingURL=bundle-BG0LKEPR.js.map
