'use strict';

var _tslib = require('./bundle-CxoFSSXv.js');
var React = require('react');
var useSendMultipleFilesMessage = require('./bundle-THfLGJxy.js');
var UserProfileContext = require('./bundle-DeyX1dvY.js');
var SendbirdContext = require('./bundle-AAO7jUU2.js');
var SendbirdChat = require('@sendbird/chat');
var pubSub_topics = require('./bundle-BPWJgESF.js');
var groupChannel = require('@sendbird/chat/groupChannel');
var uuid = require('./bundle-BUGwK1WK.js');
var compareIds = require('./bundle-CvQwksvR.js');
var Thread_context_types = require('../Thread/context/types.js');
var useSendbird = require('./bundle-LI9JjqG2.js');
var useDeepCompareEffect = require('./bundle-ChpcAmBg.js');
var message = require('@sendbird/chat/message');
require('./bundle-DDNdw3A9.js');
var consts = require('./bundle-yU9Mr2pS.js');

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

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

var PREV_THREADS_FETCH_SIZE = 30;
var NEXT_THREADS_FETCH_SIZE = 30;

function useToggleReactionCallback(_a, _b) {
    var currentChannel = _a.currentChannel;
    var logger = _b.logger;
    return React.useCallback(function (message, key, isReacted) {
        var _a, _b;
        if (isReacted) {
            (_a = currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.deleteReaction) === null || _a === void 0 ? void 0 : _a.call(currentChannel, message, key).then(function (res) {
                logger.info('Thread | useToggleReactionsCallback: Delete reaction succeeded.', res);
            }).catch(function (err) {
                logger.warning('Thread | useToggleReactionsCallback: Delete reaction failed.', err);
            });
            return;
        }
        (_b = currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.addReaction) === null || _b === void 0 ? void 0 : _b.call(currentChannel, message, key).then(function (res) {
            logger.info('Thread | useToggleReactionsCallback: Add reaction succeeded.', res);
        }).catch(function (err) {
            logger.warning('Thread | useToggleReactionsCallback: Add reaction failed.', err);
        });
    }, [currentChannel]);
}

function useSendUserMessageCallback(_a, _b) {
    var isMentionEnabled = _a.isMentionEnabled, currentChannel = _a.currentChannel, onBeforeSendUserMessage = _a.onBeforeSendUserMessage, sendMessageStart = _a.sendMessageStart, sendMessageFailure = _a.sendMessageFailure;
    var logger = _b.logger, pubSub = _b.pubSub;
    var sendMessage = React.useCallback(function (props) {
        var _a;
        var message = props.message, quoteMessage = props.quoteMessage, mentionTemplate = props.mentionTemplate, mentionedUsers = props.mentionedUsers;
        var createDefaultParams = function () {
            var params = {};
            params.message = message;
            var mentionedUsersLength = (mentionedUsers === null || mentionedUsers === void 0 ? void 0 : mentionedUsers.length) || 0;
            if (isMentionEnabled && mentionedUsersLength) {
                params.mentionedUsers = mentionedUsers;
            }
            if (isMentionEnabled && mentionTemplate && mentionedUsersLength) {
                params.mentionedMessageTemplate = mentionTemplate;
            }
            if (quoteMessage) {
                params.isReplyToChannel = true;
                params.parentMessageId = quoteMessage.messageId;
            }
            return params;
        };
        var params = (_a = onBeforeSendUserMessage === null || onBeforeSendUserMessage === void 0 ? void 0 : onBeforeSendUserMessage(message, quoteMessage)) !== null && _a !== void 0 ? _a : createDefaultParams();
        logger.info('Thread | useSendUserMessageCallback: Sending user message start.', params);
        if (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.sendUserMessage) {
            currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.sendUserMessage(params).onPending(function (pendingMessage) {
                sendMessageStart(pendingMessage);
            }).onFailed(function (error, message) {
                logger.info('Thread | useSendUserMessageCallback: Sending user message failed.', { message: message, error: error });
                sendMessageFailure(message);
            }).onSucceeded(function (message) {
                logger.info('Thread | useSendUserMessageCallback: Sending user message succeeded.', message);
                // because Thread doesn't subscribe SEND_USER_MESSAGE
                pubSub.publish(pubSub_topics.pubSubTopics.SEND_USER_MESSAGE, {
                    channel: currentChannel,
                    message: message,
                    publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
                });
            });
        }
    }, [isMentionEnabled, currentChannel]);
    return sendMessage;
}

function useSendFileMessageCallback(_a, _b) {
    var currentChannel = _a.currentChannel, onBeforeSendFileMessage = _a.onBeforeSendFileMessage, sendMessageStart = _a.sendMessageStart, sendMessageFailure = _a.sendMessageFailure;
    var logger = _b.logger, pubSub = _b.pubSub;
    return React.useCallback(function (file, quoteMessage) {
        return new Promise(function (resolve, reject) {
            var _a;
            var createParamsDefault = function () {
                var params = {};
                params.file = file;
                if (quoteMessage) {
                    params.isReplyToChannel = true;
                    params.parentMessageId = quoteMessage.messageId;
                }
                return params;
            };
            var params = (_a = onBeforeSendFileMessage === null || onBeforeSendFileMessage === void 0 ? void 0 : onBeforeSendFileMessage(file, quoteMessage)) !== null && _a !== void 0 ? _a : createParamsDefault();
            logger.info('Thread | useSendFileMessageCallback: Sending file message start.', params);
            if (currentChannel == null) {
                logger.warning('Thread | useSendFileMessageCallback: currentChannel is null. Skipping file message send.');
                resolve(null);
            }
            else {
                currentChannel.sendFileMessage(params)
                    .onPending(function (pendingMessage) {
                    // @ts-ignore
                    sendMessageStart(_tslib.__assign(_tslib.__assign({}, pendingMessage), { url: URL.createObjectURL(file), 
                        // pending thumbnail message seems to be failed
                        sendingStatus: message.SendingStatus.PENDING, isUserMessage: pendingMessage.isUserMessage, isFileMessage: pendingMessage.isFileMessage, isAdminMessage: pendingMessage.isAdminMessage, isMultipleFilesMessage: pendingMessage.isMultipleFilesMessage }));
                    setTimeout(function () { return useSendMultipleFilesMessage.scrollIntoLast(); }, consts.SCROLL_BOTTOM_DELAY_FOR_SEND);
                })
                    .onFailed(function (error, message) {
                    message.localUrl = URL.createObjectURL(file);
                    message.file = file;
                    logger.info('Thread | useSendFileMessageCallback: Sending file message failed.', { message: message, error: error });
                    sendMessageFailure(message);
                    reject(error);
                })
                    .onSucceeded(function (message) {
                    logger.info('Thread | useSendFileMessageCallback: Sending file message succeeded.', message);
                    pubSub.publish(pubSub_topics.pubSubTopics.SEND_FILE_MESSAGE, {
                        channel: currentChannel,
                        message: message,
                        publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
                    });
                    resolve(message);
                });
            }
        });
    }, [currentChannel]);
}

var useSendVoiceMessageCallback = function (_a, _b) {
    var currentChannel = _a.currentChannel, onBeforeSendVoiceMessage = _a.onBeforeSendVoiceMessage, sendMessageStart = _a.sendMessageStart, sendMessageFailure = _a.sendMessageFailure;
    var logger = _b.logger, pubSub = _b.pubSub;
    var sendMessage = React.useCallback(function (file, duration, quoteMessage) {
        var messageParams = (onBeforeSendVoiceMessage
            && typeof onBeforeSendVoiceMessage === 'function')
            ? onBeforeSendVoiceMessage(file, quoteMessage)
            : {
                file: file,
                fileName: consts.VOICE_MESSAGE_FILE_NAME,
                mimeType: consts.VOICE_MESSAGE_MIME_TYPE,
                metaArrays: [
                    new message.MessageMetaArray({
                        key: consts.META_ARRAY_VOICE_DURATION_KEY,
                        value: ["".concat(duration)],
                    }),
                    new message.MessageMetaArray({
                        key: consts.META_ARRAY_MESSAGE_TYPE_KEY,
                        value: [consts.META_ARRAY_MESSAGE_TYPE_VALUE__VOICE],
                    }),
                ],
            };
        if (quoteMessage) {
            messageParams.isReplyToChannel = true;
            messageParams.parentMessageId = quoteMessage.messageId;
        }
        logger.info('Thread | useSendVoiceMessageCallback:  Start sending voice message', messageParams);
        currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.sendFileMessage(messageParams).onPending(function (pendingMessage) {
            // @ts-ignore
            sendMessageStart(_tslib.__assign(_tslib.__assign({}, pendingMessage), { url: URL.createObjectURL(file), 
                // pending thumbnail message seems to be failed
                sendingStatus: message.SendingStatus.PENDING, isUserMessage: pendingMessage.isUserMessage, isFileMessage: pendingMessage.isFileMessage, isAdminMessage: pendingMessage.isAdminMessage, isMultipleFilesMessage: pendingMessage.isMultipleFilesMessage }));
            setTimeout(function () { return useSendMultipleFilesMessage.scrollIntoLast(); }, consts.SCROLL_BOTTOM_DELAY_FOR_SEND);
        }).onFailed(function (error, message) {
            message.localUrl = URL.createObjectURL(file);
            message.file = file;
            logger.info('Thread | useSendVoiceMessageCallback: Sending voice message failed.', { message: message, error: error });
            sendMessageFailure(message);
        }).onSucceeded(function (message) {
            logger.info('Thread | useSendVoiceMessageCallback: Sending voice message succeeded.', message);
            pubSub.publish(pubSub_topics.pubSubTopics.SEND_FILE_MESSAGE, {
                channel: currentChannel,
                message: message,
                publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
            });
        });
    }, [
        currentChannel,
        onBeforeSendVoiceMessage,
    ]);
    return sendMessage;
};

function useResendMessageCallback(_a, _b) {
    var currentChannel = _a.currentChannel, resendMessageStart = _a.resendMessageStart, sendMessageSuccess = _a.sendMessageSuccess, sendMessageFailure = _a.sendMessageFailure;
    var logger = _b.logger, pubSub = _b.pubSub;
    return React.useCallback(function (failedMessage) {
        var _a, _b, _c, _d, _e;
        if (!(failedMessage === null || failedMessage === void 0 ? void 0 : failedMessage.isResendable)) {
            logger.warning('Thread | useResendMessageCallback: Message is not resendable.', failedMessage);
            return;
        }
        logger.info('Thread | useResendMessageCallback: Resending failedMessage start.', failedMessage);
        if (((_a = failedMessage === null || failedMessage === void 0 ? void 0 : failedMessage.isUserMessage) === null || _a === void 0 ? void 0 : _a.call(failedMessage)) || (failedMessage === null || failedMessage === void 0 ? void 0 : failedMessage.messageType) === message.MessageType.USER) {
            try {
                currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.resendMessage(failedMessage).onPending(function (message) {
                    logger.info('Thread | useResendMessageCallback: Resending user message started.', message);
                    resendMessageStart(message);
                }).onSucceeded(function (message) {
                    logger.info('Thread | useResendMessageCallback: Resending user message succeeded.', message);
                    sendMessageSuccess(message);
                    pubSub.publish(pubSub_topics.pubSubTopics.SEND_USER_MESSAGE, {
                        channel: currentChannel,
                        message: message,
                        publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
                    });
                }).onFailed(function (error) {
                    logger.warning('Thread | useResendMessageCallback: Resending user message failed.', error);
                    failedMessage.sendingStatus = message.SendingStatus.FAILED;
                    sendMessageFailure(failedMessage);
                });
            }
            catch (err) {
                logger.warning('Thread | useResendMessageCallback: Resending user message failed.', err);
                failedMessage.sendingStatus = message.SendingStatus.FAILED;
                sendMessageFailure(failedMessage);
            }
        }
        else if ((_b = failedMessage === null || failedMessage === void 0 ? void 0 : failedMessage.isFileMessage) === null || _b === void 0 ? void 0 : _b.call(failedMessage)) {
            try {
                (_c = currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.resendMessage) === null || _c === void 0 ? void 0 : _c.call(currentChannel, failedMessage).onPending(function (message) {
                    logger.info('Thread | useResendMessageCallback: Resending file message started.', message);
                    resendMessageStart(message);
                }).onSucceeded(function (message) {
                    logger.info('Thread | useResendMessageCallback: Resending file message succeeded.', message);
                    sendMessageSuccess(message);
                    pubSub.publish(pubSub_topics.pubSubTopics.SEND_FILE_MESSAGE, {
                        channel: currentChannel,
                        message: failedMessage,
                        publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
                    });
                }).onFailed(function (error) {
                    logger.warning('Thread | useResendMessageCallback: Resending file message failed.', error);
                    failedMessage.sendingStatus = message.SendingStatus.FAILED;
                    sendMessageFailure(failedMessage);
                });
            }
            catch (err) {
                logger.warning('Thread | useResendMessageCallback: Resending file message failed.', err);
                failedMessage.sendingStatus = message.SendingStatus.FAILED;
                sendMessageFailure(failedMessage);
            }
        }
        else if ((_d = failedMessage === null || failedMessage === void 0 ? void 0 : failedMessage.isMultipleFilesMessage) === null || _d === void 0 ? void 0 : _d.call(failedMessage)) {
            try {
                (_e = currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.resendMessage) === null || _e === void 0 ? void 0 : _e.call(currentChannel, failedMessage).onPending(function (message) {
                    logger.info('Thread | useResendMessageCallback: Resending multiple files message started.', message);
                    resendMessageStart(message);
                }).onFileUploaded(function (requestId, index, uploadableFileInfo, error) {
                    logger.info('Thread | useResendMessageCallback: onFileUploaded during resending multiple files message.', {
                        requestId: requestId,
                        index: index,
                        error: error,
                        uploadableFileInfo: uploadableFileInfo,
                    });
                    pubSub.publish(pubSub_topics.pubSubTopics.ON_FILE_INFO_UPLOADED, {
                        response: {
                            channelUrl: currentChannel.url,
                            requestId: requestId,
                            index: index,
                            uploadableFileInfo: uploadableFileInfo,
                            error: error,
                        },
                        publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
                    });
                }).onSucceeded(function (message) {
                    logger.info('Thread | useResendMessageCallback: Resending MFM succeeded.', message);
                    sendMessageSuccess(message);
                    pubSub.publish(pubSub_topics.pubSubTopics.SEND_FILE_MESSAGE, {
                        channel: currentChannel,
                        message: message,
                        publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
                    });
                }).onFailed(function (error, message) {
                    logger.warning('Thread | useResendMessageCallback: Resending MFM failed.', error);
                    sendMessageFailure(message);
                });
            }
            catch (err) {
                logger.warning('Thread | useResendMessageCallback: Resending MFM failed.', err);
                sendMessageFailure(failedMessage);
            }
        }
        else {
            logger.warning('Thread | useResendMessageCallback: Message is not resendable.', failedMessage);
            failedMessage.sendingStatus = message.SendingStatus.FAILED;
            sendMessageFailure(failedMessage);
        }
    }, [currentChannel]);
}

function useUpdateMessageCallback(_a, _b) {
    var currentChannel = _a.currentChannel, isMentionEnabled = _a.isMentionEnabled, onMessageUpdated = _a.onMessageUpdated;
    var logger = _b.logger, pubSub = _b.pubSub;
    // TODO: add type
    return React.useCallback(function (props) {
        var _a;
        var messageId = props.messageId, message = props.message, mentionedUsers = props.mentionedUsers, mentionTemplate = props.mentionTemplate;
        var createParamsDefault = function () {
            var params = {};
            params.message = message;
            if (isMentionEnabled && mentionedUsers && (mentionedUsers === null || mentionedUsers === void 0 ? void 0 : mentionedUsers.length) > 0) {
                params.mentionedUsers = mentionedUsers;
            }
            if (isMentionEnabled && mentionTemplate) {
                params.mentionedMessageTemplate = mentionTemplate;
            }
            else {
                params.mentionedMessageTemplate = message;
            }
            return params;
        };
        var params = createParamsDefault();
        logger.info('Thread | useUpdateMessageCallback: Message update start.', params);
        if (currentChannel == null) {
            logger.warning('Thread | useUpdateMessageCallback: currentChannel is null.');
            return;
        }
        (_a = currentChannel.updateUserMessage) === null || _a === void 0 ? void 0 : _a.call(currentChannel, messageId, params).then(function (message) {
            logger.info('Thread | useUpdateMessageCallback: Message update succeeded.', message);
            onMessageUpdated(currentChannel, message);
            pubSub.publish(pubSub_topics.pubSubTopics.UPDATE_USER_MESSAGE, {
                fromSelector: true,
                channel: currentChannel,
                message: message,
                publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
            });
        });
    }, [currentChannel, isMentionEnabled]);
}

function useDeleteMessageCallback(_a, _b) {
    var currentChannel = _a.currentChannel, onMessageDeletedByReqId = _a.onMessageDeletedByReqId, onMessageDeleted = _a.onMessageDeleted;
    var logger = _b.logger;
    return React.useCallback(function (message) {
        logger.info('Thread | useDeleteMessageCallback: Deleting message.', message);
        var sendingStatus = message.sendingStatus;
        return new Promise(function (resolve, reject) {
            var _a;
            logger.info('Thread | useDeleteMessageCallback: Deleting message requestState:', sendingStatus);
            // Message is only on local
            if (sendingStatus === 'failed' || sendingStatus === 'pending') {
                logger.info('Thread | useDeleteMessageCallback: Deleted message from local:', message);
                onMessageDeletedByReqId(message.reqId);
                resolve();
            }
            if (currentChannel == null) {
                logger.info('Thread | useDeleteMessageCallback: No current channel');
                resolve();
            }
            logger.info('Thread | useDeleteMessageCallback: Deleting message from remote:', sendingStatus);
            (_a = currentChannel.deleteMessage) === null || _a === void 0 ? void 0 : _a.call(currentChannel, message).then(function () {
                logger.info('Thread | useDeleteMessageCallback: Deleting message success!', message);
                onMessageDeleted(currentChannel, message.messageId);
                resolve();
            }).catch(function (err) {
                logger.warning('Thread | useDeleteMessageCallback: Deleting message failed!', err);
                reject(err);
            });
        });
    }, [currentChannel]);
}

function getThreadMessageListParams(params) {
    return _tslib.__assign({ prevResultSize: PREV_THREADS_FETCH_SIZE, nextResultSize: NEXT_THREADS_FETCH_SIZE, includeMetaArray: true }, params);
}
var useThreadFetchers = function (_a) {
    var isReactionEnabled = _a.isReactionEnabled, anchorMessage = _a.anchorMessage, staleParentMessage = _a.parentMessage, logger = _a.logger, oldestMessageTimeStamp = _a.oldestMessageTimeStamp, latestMessageTimeStamp = _a.latestMessageTimeStamp, threadListState = _a.threadListState, initializeThreadListStart = _a.initializeThreadListStart, initializeThreadListSuccess = _a.initializeThreadListSuccess, initializeThreadListFailure = _a.initializeThreadListFailure, getPrevMessagesStart = _a.getPrevMessagesStart, getPrevMessagesSuccess = _a.getPrevMessagesSuccess, getPrevMessagesFailure = _a.getPrevMessagesFailure, getNextMessagesStart = _a.getNextMessagesStart, getNextMessagesSuccess = _a.getNextMessagesSuccess, getNextMessagesFailure = _a.getNextMessagesFailure;
    var stores = useSendbird.useSendbird().state.stores;
    var timestamp = (anchorMessage === null || anchorMessage === void 0 ? void 0 : anchorMessage.createdAt) || 0;
    var initialize = React.useCallback(function (callback) { return _tslib.__awaiter(void 0, void 0, void 0, function () {
        var params, _a, threadedMessages_1, parentMessage, error_1;
        return _tslib.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!stores.sdkStore.initialized || !staleParentMessage)
                        return [2 /*return*/];
                    initializeThreadListStart();
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 3, , 4]);
                    params = getThreadMessageListParams({ includeReactions: isReactionEnabled });
                    logger.info('Thread | useGetThreadList: Initialize thread list start.', { timestamp: timestamp, params: params });
                    return [4 /*yield*/, staleParentMessage.getThreadedMessagesByTimestamp(timestamp, params)];
                case 2:
                    _a = _b.sent(), threadedMessages_1 = _a.threadedMessages, parentMessage = _a.parentMessage;
                    logger.info('Thread | useGetThreadList: Initialize thread list succeeded.', { staleParentMessage: staleParentMessage, threadedMessages: threadedMessages_1 });
                    initializeThreadListSuccess(parentMessage, anchorMessage, threadedMessages_1);
                    setTimeout(function () { return callback === null || callback === void 0 ? void 0 : callback(threadedMessages_1); });
                    return [3 /*break*/, 4];
                case 3:
                    error_1 = _b.sent();
                    logger.info('Thread | useGetThreadList: Initialize thread list failed.', error_1);
                    initializeThreadListFailure();
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/];
            }
        });
    }); }, [stores.sdkStore.initialized, staleParentMessage, anchorMessage, isReactionEnabled]);
    var loadPrevious = React.useCallback(function (callback) { return _tslib.__awaiter(void 0, void 0, void 0, function () {
        var params, _a, threadedMessages_2, parentMessage, error_2;
        return _tslib.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (threadListState !== Thread_context_types.ThreadListStateTypes.INITIALIZED || oldestMessageTimeStamp === 0 || !staleParentMessage)
                        return [2 /*return*/];
                    getPrevMessagesStart();
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 3, , 4]);
                    params = getThreadMessageListParams({ nextResultSize: 0, includeReactions: isReactionEnabled });
                    return [4 /*yield*/, staleParentMessage.getThreadedMessagesByTimestamp(oldestMessageTimeStamp, params)];
                case 2:
                    _a = _b.sent(), threadedMessages_2 = _a.threadedMessages, parentMessage = _a.parentMessage;
                    logger.info('Thread | useGetPrevThreadsCallback: Fetch prev threads succeeded.', { parentMessage: parentMessage, threadedMessages: threadedMessages_2 });
                    getPrevMessagesSuccess(threadedMessages_2);
                    setTimeout(function () { return callback === null || callback === void 0 ? void 0 : callback(threadedMessages_2); });
                    return [3 /*break*/, 4];
                case 3:
                    error_2 = _b.sent();
                    logger.info('Thread | useGetPrevThreadsCallback: Fetch prev threads failed.', error_2);
                    getPrevMessagesFailure();
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/];
            }
        });
    }); }, [threadListState, oldestMessageTimeStamp, isReactionEnabled, staleParentMessage]);
    var loadNext = React.useCallback(function (callback) { return _tslib.__awaiter(void 0, void 0, void 0, function () {
        var params, _a, threadedMessages_3, parentMessage, error_3;
        return _tslib.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (threadListState !== Thread_context_types.ThreadListStateTypes.INITIALIZED || latestMessageTimeStamp === 0 || !staleParentMessage)
                        return [2 /*return*/];
                    getNextMessagesStart();
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 3, , 4]);
                    params = getThreadMessageListParams({ prevResultSize: 0, includeReactions: isReactionEnabled });
                    return [4 /*yield*/, staleParentMessage.getThreadedMessagesByTimestamp(latestMessageTimeStamp, params)];
                case 2:
                    _a = _b.sent(), threadedMessages_3 = _a.threadedMessages, parentMessage = _a.parentMessage;
                    logger.info('Thread | useGetNextThreadsCallback: Fetch next threads succeeded.', { parentMessage: parentMessage, threadedMessages: threadedMessages_3 });
                    getNextMessagesSuccess(threadedMessages_3);
                    setTimeout(function () { return callback === null || callback === void 0 ? void 0 : callback(threadedMessages_3); });
                    return [3 /*break*/, 4];
                case 3:
                    error_3 = _b.sent();
                    logger.info('Thread | useGetNextThreadsCallback: Fetch next threads failed.', error_3);
                    getNextMessagesFailure();
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/];
            }
        });
    }); }, [threadListState, latestMessageTimeStamp, isReactionEnabled, staleParentMessage]);
    return {
        initializeThreadFetcher: initialize,
        fetchPrevThreads: loadPrevious,
        fetchNextThreads: loadNext,
    };
};

function hasReqId(message) {
    return 'reqId' in message;
}
var useThread = function () {
    var _a, _b;
    var store = React.useContext(ThreadContext);
    if (!store)
        throw new Error('useThread must be used within a ThreadProvider');
    // SendbirdStateContext config
    var _c = useSendbird.useSendbird().state, stores = _c.stores, config = _c.config;
    var logger = config.logger, pubSub = config.pubSub;
    var isMentionEnabled = config.groupChannel.enableMention;
    var isReactionEnabled = config.groupChannel.enableReactions;
    var state = SendbirdContext.shimExports.useSyncExternalStore(store.subscribe, store.getState);
    var message = state.message, parentMessage = state.parentMessage, currentChannel = state.currentChannel, threadListState = state.threadListState, allThreadMessages = state.allThreadMessages, onBeforeSendUserMessage = state.onBeforeSendUserMessage, onBeforeSendFileMessage = state.onBeforeSendFileMessage, onBeforeSendVoiceMessage = state.onBeforeSendVoiceMessage, onBeforeSendMultipleFilesMessage = state.onBeforeSendMultipleFilesMessage;
    var sendMessageStatusActions = {
        sendMessageStart: function (message) { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { localThreadMessages: _tslib.__spreadArray(_tslib.__spreadArray([], state.localThreadMessages, true), [
                    message,
                ], false) });
        }); },
        sendMessageSuccess: function (message) { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { allThreadMessages: _tslib.__spreadArray(_tslib.__spreadArray([], state.allThreadMessages.filter(function (m) { return (!useSendMultipleFilesMessage.compareIds(m === null || m === void 0 ? void 0 : m.reqId, message === null || message === void 0 ? void 0 : message.reqId)); }), true), [
                    message,
                ], false), localThreadMessages: state.localThreadMessages.filter(function (m) { return (!useSendMultipleFilesMessage.compareIds(m === null || m === void 0 ? void 0 : m.reqId, message === null || message === void 0 ? void 0 : message.reqId)); }) });
        }); },
        sendMessageFailure: function (message) { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { localThreadMessages: state.localThreadMessages.map(function (m) { return (useSendMultipleFilesMessage.compareIds(m === null || m === void 0 ? void 0 : m.reqId, message === null || message === void 0 ? void 0 : message.reqId)
                    ? message
                    : m); }) });
        }); },
        resendMessageStart: function (message) { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { localThreadMessages: state.localThreadMessages.map(function (m) { return (useSendMultipleFilesMessage.compareIds(m === null || m === void 0 ? void 0 : m.reqId, message === null || message === void 0 ? void 0 : message.reqId)
                    ? message
                    : m); }) });
        }); },
    };
    var toggleReaction = useToggleReactionCallback({ currentChannel: currentChannel }, { logger: logger });
    var sendMessageActions = {
        sendMessage: useSendUserMessageCallback({
            isMentionEnabled: isMentionEnabled,
            currentChannel: currentChannel,
            onBeforeSendUserMessage: onBeforeSendUserMessage,
            sendMessageStart: sendMessageStatusActions.sendMessageStart,
            sendMessageFailure: sendMessageStatusActions.sendMessageFailure,
        }, {
            logger: logger,
            pubSub: pubSub,
        }),
        sendFileMessage: useSendFileMessageCallback({
            currentChannel: currentChannel,
            onBeforeSendFileMessage: onBeforeSendFileMessage,
            sendMessageStart: sendMessageStatusActions.sendMessageStart,
            sendMessageFailure: sendMessageStatusActions.sendMessageFailure,
        }, {
            logger: logger,
            pubSub: pubSub,
        }),
        sendVoiceMessage: useSendVoiceMessageCallback({
            currentChannel: currentChannel,
            onBeforeSendVoiceMessage: onBeforeSendVoiceMessage,
            sendMessageStart: sendMessageStatusActions.sendMessageStart,
            sendMessageFailure: sendMessageStatusActions.sendMessageFailure,
        }, {
            logger: logger,
            pubSub: pubSub,
        }),
        sendMultipleFilesMessage: useSendMultipleFilesMessage.useSendMultipleFilesMessage({
            currentChannel: currentChannel,
            onBeforeSendMultipleFilesMessage: onBeforeSendMultipleFilesMessage,
            publishingModules: [pubSub_topics.PublishingModuleType.THREAD],
        }, {
            logger: logger,
            pubSub: pubSub,
        })[0],
        resendMessage: useResendMessageCallback({
            resendMessageStart: sendMessageStatusActions.resendMessageStart,
            sendMessageSuccess: sendMessageStatusActions.sendMessageSuccess,
            sendMessageFailure: sendMessageStatusActions.sendMessageFailure,
            currentChannel: currentChannel,
        }, { logger: logger, pubSub: pubSub }),
    };
    var messageModifiedActions = {
        onMessageUpdated: function (channel, message) { return store.setState(function (state) {
            var _a, _b, _c;
            if (((_a = state.currentChannel) === null || _a === void 0 ? void 0 : _a.url) !== (channel === null || channel === void 0 ? void 0 : channel.url)) {
                return state;
            }
            return _tslib.__assign(_tslib.__assign({}, state), { parentMessage: ((_b = state.parentMessage) === null || _b === void 0 ? void 0 : _b.messageId) === (message === null || message === void 0 ? void 0 : message.messageId)
                    ? message
                    : state.parentMessage, allThreadMessages: (_c = state.allThreadMessages) === null || _c === void 0 ? void 0 : _c.map(function (msg) { return (((msg === null || msg === void 0 ? void 0 : msg.messageId) === (message === null || message === void 0 ? void 0 : message.messageId)) ? message : msg); }) });
        }); },
        onMessageDeleted: function (channel, messageId) { return store.setState(function (state) {
            var _a, _b, _c, _d;
            if (((_a = state.currentChannel) === null || _a === void 0 ? void 0 : _a.url) !== (channel === null || channel === void 0 ? void 0 : channel.url)) {
                return state;
            }
            if (((_b = state === null || state === void 0 ? void 0 : state.parentMessage) === null || _b === void 0 ? void 0 : _b.messageId) === messageId) {
                return _tslib.__assign(_tslib.__assign({}, state), { parentMessage: null, parentMessageState: Thread_context_types.ParentMessageStateTypes.NIL, allThreadMessages: [] });
            }
            return _tslib.__assign(_tslib.__assign({}, state), { allThreadMessages: (_c = state.allThreadMessages) === null || _c === void 0 ? void 0 : _c.filter(function (msg) { return ((msg === null || msg === void 0 ? void 0 : msg.messageId) !== messageId); }), localThreadMessages: (_d = state.localThreadMessages) === null || _d === void 0 ? void 0 : _d.filter(function (msg) { return ((msg === null || msg === void 0 ? void 0 : msg.messageId) !== messageId); }) });
        }); },
        onMessageDeletedByReqId: function (reqId) { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { localThreadMessages: state.localThreadMessages.filter(function (m) { return (!useSendMultipleFilesMessage.compareIds(m.reqId, reqId)); }) });
        }); },
    };
    var modifyMessageActions = {
        updateMessage: useUpdateMessageCallback({
            currentChannel: currentChannel,
            isMentionEnabled: isMentionEnabled,
            onMessageUpdated: messageModifiedActions.onMessageUpdated,
        }, { logger: logger, pubSub: pubSub }),
        deleteMessage: useDeleteMessageCallback({
            currentChannel: currentChannel,
            onMessageDeleted: messageModifiedActions.onMessageDeleted,
            onMessageDeletedByReqId: messageModifiedActions.onMessageDeletedByReqId,
        }, { logger: logger }),
    };
    var threadFetcherStatusActions = {
        initializeThreadListStart: function () { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { threadListState: Thread_context_types.ThreadListStateTypes.LOADING, allThreadMessages: [] });
        }); },
        initializeThreadListSuccess: function (parentMessage, anchorMessage, threadedMessages) { return store.setState(function (state) {
            var anchorMessageCreatedAt = (!(anchorMessage === null || anchorMessage === void 0 ? void 0 : anchorMessage.messageId)) ? parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.createdAt : anchorMessage === null || anchorMessage === void 0 ? void 0 : anchorMessage.createdAt;
            var anchorIndex = threadedMessages.findIndex(function (message) { return (message === null || message === void 0 ? void 0 : message.createdAt) > anchorMessageCreatedAt; });
            var prevThreadMessages = anchorIndex > -1 ? threadedMessages.slice(0, anchorIndex) : threadedMessages;
            var anchorThreadMessage = (anchorMessage === null || anchorMessage === void 0 ? void 0 : anchorMessage.messageId) ? [anchorMessage] : [];
            var nextThreadMessages = anchorIndex > -1 ? threadedMessages.slice(anchorIndex) : [];
            return _tslib.__assign(_tslib.__assign({}, state), { threadListState: Thread_context_types.ThreadListStateTypes.INITIALIZED, hasMorePrev: anchorIndex === -1 || anchorIndex === PREV_THREADS_FETCH_SIZE, hasMoreNext: threadedMessages.length - anchorIndex === NEXT_THREADS_FETCH_SIZE, allThreadMessages: [prevThreadMessages, anchorThreadMessage, nextThreadMessages].flat() });
        }); },
        initializeThreadListFailure: function () { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { threadListState: Thread_context_types.ThreadListStateTypes.LOADING, allThreadMessages: [] });
        }); },
        getPrevMessagesStart: function () { return store.setState(function (state) {
            return _tslib.__assign({}, state);
        }); },
        getPrevMessagesSuccess: function (threadedMessages) { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { hasMorePrev: threadedMessages.length === PREV_THREADS_FETCH_SIZE, allThreadMessages: _tslib.__spreadArray(_tslib.__spreadArray([], threadedMessages, true), state.allThreadMessages, true) });
        }); },
        getPrevMessagesFailure: function () { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { hasMorePrev: false });
        }); },
        getNextMessagesStart: function () { return store.setState(function (state) {
            return _tslib.__assign({}, state);
        }); },
        getNextMessagesSuccess: function (threadedMessages) { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { hasMoreNext: threadedMessages.length === NEXT_THREADS_FETCH_SIZE, allThreadMessages: _tslib.__spreadArray(_tslib.__spreadArray([], state.allThreadMessages, true), threadedMessages, true) });
        }); },
        getNextMessagesFailure: function () { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { hasMoreNext: false });
        }); },
    };
    var _d = useThreadFetchers({
        parentMessage: parentMessage,
        // anchorMessage should be null when parentMessage doesn't exist
        anchorMessage: (message === null || message === void 0 ? void 0 : message.messageId) !== (parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.messageId) ? message || undefined : undefined,
        logger: logger,
        isReactionEnabled: isReactionEnabled,
        threadListState: threadListState,
        oldestMessageTimeStamp: ((_a = allThreadMessages[0]) === null || _a === void 0 ? void 0 : _a.createdAt) || 0,
        latestMessageTimeStamp: ((_b = allThreadMessages[allThreadMessages.length - 1]) === null || _b === void 0 ? void 0 : _b.createdAt) || 0,
        initializeThreadListStart: threadFetcherStatusActions.initializeThreadListStart,
        initializeThreadListSuccess: threadFetcherStatusActions.initializeThreadListSuccess,
        initializeThreadListFailure: threadFetcherStatusActions.initializeThreadListFailure,
        getPrevMessagesStart: threadFetcherStatusActions.getPrevMessagesStart,
        getPrevMessagesSuccess: threadFetcherStatusActions.getPrevMessagesSuccess,
        getPrevMessagesFailure: threadFetcherStatusActions.getPrevMessagesFailure,
        getNextMessagesStart: threadFetcherStatusActions.getNextMessagesStart,
        getNextMessagesSuccess: threadFetcherStatusActions.getNextMessagesSuccess,
        getNextMessagesFailure: threadFetcherStatusActions.getNextMessagesFailure,
    }), initializeThreadFetcher = _d.initializeThreadFetcher, fetchPrevThreads = _d.fetchPrevThreads, fetchNextThreads = _d.fetchNextThreads;
    var actions = React.useMemo(function () { return (_tslib.__assign(_tslib.__assign(_tslib.__assign(_tslib.__assign(_tslib.__assign(_tslib.__assign({ setCurrentUserId: function (currentUserId) { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { currentUserId: currentUserId })); }); }, getChannelStart: function () { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { channelState: Thread_context_types.ChannelStateTypes.LOADING, currentChannel: null })); }); }, getChannelSuccess: function (groupChannel) { return store.setState(function (state) {
            var _a, _b;
            return (_tslib.__assign(_tslib.__assign({}, state), { channelState: Thread_context_types.ChannelStateTypes.INITIALIZED, currentChannel: groupChannel, 
                // only support in normal group channel
                isMuted: ((_b = (_a = groupChannel === null || groupChannel === void 0 ? void 0 : groupChannel.members) === null || _a === void 0 ? void 0 : _a.find(function (member) { return (member === null || member === void 0 ? void 0 : member.userId) === state.currentUserId; })) === null || _b === void 0 ? void 0 : _b.isMuted) || false, isChannelFrozen: (groupChannel === null || groupChannel === void 0 ? void 0 : groupChannel.isFrozen) || false }));
        }); }, getChannelFailure: function () { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { channelState: Thread_context_types.ChannelStateTypes.INVALID, currentChannel: null })); }); }, getParentMessageStart: function () { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { parentMessageState: Thread_context_types.ParentMessageStateTypes.LOADING, parentMessage: null })); }); }, getParentMessageSuccess: function (parentMessage) { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { parentMessageState: Thread_context_types.ParentMessageStateTypes.INITIALIZED, parentMessage: parentMessage })); }); }, getParentMessageFailure: function () { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { parentMessageState: Thread_context_types.ParentMessageStateTypes.INVALID, parentMessage: null })); }); }, setEmojiContainer: function (emojiContainer) { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { emojiContainer: emojiContainer })); }); }, onMessageReceived: function (channel, message) { return store.setState(function (state) {
            var _a, _b, _c, _d;
            if (((_a = state.currentChannel) === null || _a === void 0 ? void 0 : _a.url) !== (channel === null || channel === void 0 ? void 0 : channel.url)
                || state.hasMoreNext
                || ((_b = message === null || message === void 0 ? void 0 : message.parentMessage) === null || _b === void 0 ? void 0 : _b.messageId) !== ((_c = state === null || state === void 0 ? void 0 : state.parentMessage) === null || _c === void 0 ? void 0 : _c.messageId)) {
                return state;
            }
            var isAlreadyReceived = state.allThreadMessages.findIndex(function (m) { return (m.messageId === message.messageId); }) > -1;
            return _tslib.__assign(_tslib.__assign({}, state), { parentMessage: ((_d = state.parentMessage) === null || _d === void 0 ? void 0 : _d.messageId) === (message === null || message === void 0 ? void 0 : message.messageId) ? message : state.parentMessage, allThreadMessages: isAlreadyReceived
                    ? state.allThreadMessages.map(function (m) { return (m.messageId === message.messageId ? message : m); })
                    : _tslib.__spreadArray(_tslib.__spreadArray([], state.allThreadMessages.filter(function (m) { return (m === null || m === void 0 ? void 0 : m.reqId) !== (message === null || message === void 0 ? void 0 : message.reqId); }), true), [
                        message,
                    ], false) });
        }); }, onReactionUpdated: function (reactionEvent) { return store.setState(function (state) {
            var _a, _b, _c;
            if (((_a = state === null || state === void 0 ? void 0 : state.parentMessage) === null || _a === void 0 ? void 0 : _a.messageId) === (reactionEvent === null || reactionEvent === void 0 ? void 0 : reactionEvent.messageId)) {
                (_c = (_b = state.parentMessage) === null || _b === void 0 ? void 0 : _b.applyReactionEvent) === null || _c === void 0 ? void 0 : _c.call(_b, reactionEvent);
            }
            return _tslib.__assign(_tslib.__assign({}, state), { allThreadMessages: state.allThreadMessages.map(function (m) {
                    var _a;
                    if ((reactionEvent === null || reactionEvent === void 0 ? void 0 : reactionEvent.messageId) === (m === null || m === void 0 ? void 0 : m.messageId)) {
                        (_a = m === null || m === void 0 ? void 0 : m.applyReactionEvent) === null || _a === void 0 ? void 0 : _a.call(m, reactionEvent);
                        return m;
                    }
                    return m;
                }) });
        }); }, onUserMuted: function (channel, user) { return store.setState(function (state) {
            var _a;
            if (((_a = state.currentChannel) === null || _a === void 0 ? void 0 : _a.url) !== (channel === null || channel === void 0 ? void 0 : channel.url) || state.currentUserId !== (user === null || user === void 0 ? void 0 : user.userId)) {
                return state;
            }
            return _tslib.__assign(_tslib.__assign({}, state), { isMuted: true });
        }); }, onUserUnmuted: function (channel, user) { return store.setState(function (state) {
            var _a;
            if (((_a = state.currentChannel) === null || _a === void 0 ? void 0 : _a.url) !== (channel === null || channel === void 0 ? void 0 : channel.url) || state.currentUserId !== (user === null || user === void 0 ? void 0 : user.userId)) {
                return state;
            }
            return _tslib.__assign(_tslib.__assign({}, state), { isMuted: false });
        }); }, onUserBanned: function () { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { channelState: Thread_context_types.ChannelStateTypes.NIL, threadListState: Thread_context_types.ThreadListStateTypes.NIL, parentMessageState: Thread_context_types.ParentMessageStateTypes.NIL, currentChannel: null, parentMessage: null, allThreadMessages: [], hasMorePrev: false, hasMoreNext: false });
        }); }, onUserUnbanned: function () { return store.setState(function (state) {
            return _tslib.__assign({}, state);
        }); }, onUserLeft: function () { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { channelState: Thread_context_types.ChannelStateTypes.NIL, threadListState: Thread_context_types.ThreadListStateTypes.NIL, parentMessageState: Thread_context_types.ParentMessageStateTypes.NIL, currentChannel: null, parentMessage: null, allThreadMessages: [], hasMorePrev: false, hasMoreNext: false });
        }); }, onChannelFrozen: function () { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { isChannelFrozen: true });
        }); }, onChannelUnfrozen: function () { return store.setState(function (state) {
            return _tslib.__assign(_tslib.__assign({}, state), { isChannelFrozen: false });
        }); }, onOperatorUpdated: function (channel) { return store.setState(function (state) {
            var _a;
            if ((channel === null || channel === void 0 ? void 0 : channel.url) === ((_a = state.currentChannel) === null || _a === void 0 ? void 0 : _a.url)) {
                return _tslib.__assign(_tslib.__assign({}, state), { currentChannel: channel });
            }
            return state;
        }); }, onTypingStatusUpdated: function (channel, typingMembers) { return store.setState(function (state) {
            var _a;
            if (!useSendMultipleFilesMessage.compareIds(channel.url, (_a = state.currentChannel) === null || _a === void 0 ? void 0 : _a.url)) {
                return state;
            }
            return _tslib.__assign(_tslib.__assign({}, state), { typingMembers: typingMembers });
        }); }, onFileInfoUpdated: function (_a) {
            var channelUrl = _a.channelUrl, requestId = _a.requestId, index = _a.index, uploadableFileInfo = _a.uploadableFileInfo, error = _a.error;
            return store.setState(function (state) {
                var _a, _b;
                if (!useSendMultipleFilesMessage.compareIds(channelUrl, (_a = state.currentChannel) === null || _a === void 0 ? void 0 : _a.url)) {
                    return state;
                }
                /**
                 * We don't have to do anything here because
                 * onFailed() will be called so handle error there instead.
                 */
                if (error)
                    return state;
                var localThreadMessages = state.localThreadMessages;
                var messageToUpdate = localThreadMessages.find(function (message) { return useSendMultipleFilesMessage.compareIds(hasReqId(message) && message.reqId, requestId); });
                var fileInfoList = (_b = messageToUpdate
                    .messageParams) === null || _b === void 0 ? void 0 : _b.fileInfoList;
                if (Array.isArray(fileInfoList)) {
                    fileInfoList[index] = uploadableFileInfo;
                }
                return _tslib.__assign(_tslib.__assign({}, state), { localThreadMessages: localThreadMessages });
            });
        }, toggleReaction: toggleReaction }, sendMessageStatusActions), sendMessageActions), messageModifiedActions), modifyMessageActions), threadFetcherStatusActions), { initializeThreadFetcher: initializeThreadFetcher, fetchPrevThreads: fetchPrevThreads, fetchNextThreads: fetchNextThreads })); }, [
        store,
        currentChannel,
        stores.sdkStore.initialized,
        parentMessage,
    ]);
    return { state: state, actions: actions };
};

function useGetChannel(_a, _b) {
    var channelUrl = _a.channelUrl, sdkInit = _a.sdkInit, message = _a.message;
    var sdk = _b.sdk, logger = _b.logger;
    var _c = useThread().actions, getChannelStart = _c.getChannelStart, getChannelSuccess = _c.getChannelSuccess, getChannelFailure = _c.getChannelFailure;
    React.useEffect(function () {
        var _a, _b;
        // validation check
        if (sdkInit && channelUrl && (sdk === null || sdk === void 0 ? void 0 : sdk.groupChannel)) {
            logger.info('Thread | useInitialize: Get channel started');
            getChannelStart();
            (_b = (_a = sdk.groupChannel).getChannel) === null || _b === void 0 ? void 0 : _b.call(_a, channelUrl).then(function (groupChannel) {
                logger.info('Thread | useInitialize: Get channel succeeded', groupChannel);
                getChannelSuccess(groupChannel);
            }).catch(function (error) {
                logger.info('Thread | useInitialize: Get channel failed', error);
                getChannelFailure();
            });
        }
    }, [message, sdkInit]);
    /**
     * We don't use channelUrl here,
     * because Thread must operate independently of the channel.
     */
}

function useGetAllEmoji(_a, _b) {
    var sdk = _a.sdk;
    var logger = _b.logger;
    var setEmojiContainer = useThread().actions.setEmojiContainer;
    React.useEffect(function () {
        if (sdk === null || sdk === void 0 ? void 0 : sdk.getAllEmoji) { // validation check
            sdk === null || sdk === void 0 ? void 0 : sdk.getAllEmoji().then(function (emojiContainer) {
                logger.info('Thread | useGetAllEmoji: Getting emojis succeeded.', emojiContainer);
                setEmojiContainer(emojiContainer);
            }).catch(function (error) {
                logger.info('Thread | useGetAllEmoji: Getting emojis failed.', error);
            });
        }
    }, [sdk]);
}

function useGetParentMessage(_a, _b) {
    var channelUrl = _a.channelUrl, sdkInit = _a.sdkInit, parentMessage = _a.parentMessage;
    var sdk = _b.sdk, logger = _b.logger;
    var _c = useThread().actions, getParentMessageStart = _c.getParentMessageStart, getParentMessageSuccess = _c.getParentMessageSuccess, getParentMessageFailure = _c.getParentMessageFailure;
    React.useEffect(function () {
        var _a, _b, _c;
        // validation check
        if (sdkInit && ((_a = sdk === null || sdk === void 0 ? void 0 : sdk.message) === null || _a === void 0 ? void 0 : _a.getMessage) && parentMessage) {
            getParentMessageStart();
            var params = {
                channelUrl: channelUrl,
                channelType: SendbirdChat.ChannelType.GROUP,
                messageId: parentMessage.messageId,
                includeMetaArray: true,
                includeReactions: true,
                includeThreadInfo: true,
                includeParentMessageInfo: true,
            };
            logger.info('Thread | useGetParentMessage: Get parent message start.', params);
            (_c = (_b = sdk.message).getMessage) === null || _c === void 0 ? void 0 : _c.call(_b, params).then(function (parentMsg) {
                logger.info('Thread | useGetParentMessage: Get parent message succeeded.', parentMessage);
                // @ts-ignore
                parentMsg.ogMetaData = (parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.ogMetaData) || null; // ogMetaData is not included for now
                // @ts-ignore
                getParentMessageSuccess(parentMsg);
            }).catch(function (error) {
                logger.info('Thread | useGetParentMessage: Get parent message failed.', error);
                getParentMessageFailure();
            });
        }
    }, [sdkInit, parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.messageId]);
    /**
     * We don't use channelUrl here,
     * because Thread must operate independently of the channel.
     */
}

function useHandleThreadPubsubEvents(_a, _b) {
    var sdkInit = _a.sdkInit, currentChannel = _a.currentChannel, parentMessage = _a.parentMessage;
    var pubSub = _b.pubSub;
    var _c = useThread().actions, sendMessageStart = _c.sendMessageStart, sendMessageSuccess = _c.sendMessageSuccess, sendMessageFailure = _c.sendMessageFailure, onFileInfoUpdated = _c.onFileInfoUpdated, onMessageUpdated = _c.onMessageUpdated, onMessageDeleted = _c.onMessageDeleted;
    React.useEffect(function () {
        var subscriber = new Map();
        if (pubSub === null || pubSub === void 0 ? void 0 : pubSub.subscribe) {
            // TODO: subscribe ON_FILE_INFO_UPLOADED
            subscriber.set(pubSub_topics.pubSubTopics.SEND_MESSAGE_START, pubSub.subscribe(pubSub_topics.pubSubTopics.SEND_MESSAGE_START, function (props) {
                var _a, _b;
                var channel = props.channel, message = props.message, publishingModules = props.publishingModules;
                if ((currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) === (channel === null || channel === void 0 ? void 0 : channel.url) && (message === null || message === void 0 ? void 0 : message.parentMessageId) === (parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.messageId) && pubSub_topics.shouldPubSubPublishToThread(publishingModules)) {
                    // TODO: const clonedMessage = cloneMessage(message);
                    var pendingMessage = _tslib.__assign({}, message);
                    if (message.isMultipleFilesMessage()) {
                        pendingMessage.fileInfoList = (_b = (_a = message === null || message === void 0 ? void 0 : message.messageParams) === null || _a === void 0 ? void 0 : _a.fileInfoList.map(function (fileInfo) { return (_tslib.__assign(_tslib.__assign({}, fileInfo), { url: URL.createObjectURL(fileInfo.file) })); })) !== null && _b !== void 0 ? _b : [];
                    }
                    sendMessageStart(message);
                }
                useSendMultipleFilesMessage.scrollIntoLast === null || useSendMultipleFilesMessage.scrollIntoLast === void 0 ? void 0 : useSendMultipleFilesMessage.scrollIntoLast();
            }));
            subscriber.set(pubSub_topics.PUBSUB_TOPICS.ON_FILE_INFO_UPLOADED, pubSub.subscribe(pubSub_topics.PUBSUB_TOPICS.ON_FILE_INFO_UPLOADED, function (props) {
                var response = props.response, publishingModules = props.publishingModules;
                if ((currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) === response.channelUrl && pubSub_topics.shouldPubSubPublishToThread(publishingModules)) {
                    onFileInfoUpdated(response);
                }
            }));
            subscriber.set(pubSub_topics.pubSubTopics.SEND_USER_MESSAGE, pubSub.subscribe(pubSub_topics.pubSubTopics.SEND_USER_MESSAGE, function (props) {
                var _a = props, channel = _a.channel, message = _a.message;
                if ((currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) === (channel === null || channel === void 0 ? void 0 : channel.url)
                    && (message === null || message === void 0 ? void 0 : message.parentMessageId) === (parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.messageId)) {
                    sendMessageSuccess(message);
                }
                useSendMultipleFilesMessage.scrollIntoLast === null || useSendMultipleFilesMessage.scrollIntoLast === void 0 ? void 0 : useSendMultipleFilesMessage.scrollIntoLast();
            }));
            subscriber.set(pubSub_topics.pubSubTopics.SEND_MESSAGE_FAILED, pubSub.subscribe(pubSub_topics.pubSubTopics.SEND_MESSAGE_FAILED, function (props) {
                var channel = props.channel, message = props.message, publishingModules = props.publishingModules;
                if ((currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) === (channel === null || channel === void 0 ? void 0 : channel.url) && (message === null || message === void 0 ? void 0 : message.parentMessageId) === (parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.messageId) && pubSub_topics.shouldPubSubPublishToThread(publishingModules)) {
                    sendMessageFailure(message);
                }
            }));
            subscriber.set(pubSub_topics.pubSubTopics.SEND_FILE_MESSAGE, pubSub.subscribe(pubSub_topics.pubSubTopics.SEND_FILE_MESSAGE, function (props) {
                var channel = props.channel, message = props.message, publishingModules = props.publishingModules;
                if ((currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) === (channel === null || channel === void 0 ? void 0 : channel.url) && pubSub_topics.shouldPubSubPublishToThread(publishingModules)) {
                    sendMessageSuccess(message);
                }
                useSendMultipleFilesMessage.scrollIntoLast === null || useSendMultipleFilesMessage.scrollIntoLast === void 0 ? void 0 : useSendMultipleFilesMessage.scrollIntoLast();
            }));
            subscriber.set(pubSub_topics.pubSubTopics.UPDATE_USER_MESSAGE, pubSub.subscribe(pubSub_topics.pubSubTopics.UPDATE_USER_MESSAGE, function (props) {
                var _a = props, channel = _a.channel, message = _a.message;
                if ((currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url) === (channel === null || channel === void 0 ? void 0 : channel.url)) {
                    onMessageUpdated(channel, message);
                }
            }));
            subscriber.set(pubSub_topics.pubSubTopics.DELETE_MESSAGE, pubSub.subscribe(pubSub_topics.pubSubTopics.DELETE_MESSAGE, function (props) {
                var _a = props, channel = _a.channel, messageId = _a.messageId;
                onMessageDeleted(channel, messageId);
            }));
        }
        return function () {
            subscriber === null || subscriber === void 0 ? void 0 : subscriber.forEach(function (s) {
                try {
                    s === null || s === void 0 ? void 0 : s.remove();
                }
                catch (_a) {
                    //
                }
            });
        };
    }, [sdkInit, currentChannel, parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.messageId]);
}

function useHandleChannelEvents(_a, _b) {
    var sdk = _a.sdk, currentChannel = _a.currentChannel;
    var logger = _b.logger;
    var _c = useThread().actions, onMessageReceived = _c.onMessageReceived, onMessageUpdated = _c.onMessageUpdated, onMessageDeleted = _c.onMessageDeleted, onReactionUpdated = _c.onReactionUpdated, onUserMuted = _c.onUserMuted, onUserUnmuted = _c.onUserUnmuted, onUserBanned = _c.onUserBanned, onUserUnbanned = _c.onUserUnbanned, onUserLeft = _c.onUserLeft, onChannelFrozen = _c.onChannelFrozen, onChannelUnfrozen = _c.onChannelUnfrozen, onOperatorUpdated = _c.onOperatorUpdated, onTypingStatusUpdated = _c.onTypingStatusUpdated;
    React.useEffect(function () {
        var _a, _b, _c;
        var handlerId = uuid.uuidv4();
        // validation check
        if (((_a = sdk === null || sdk === void 0 ? void 0 : sdk.groupChannel) === null || _a === void 0 ? void 0 : _a.addGroupChannelHandler)
            && currentChannel) {
            var channelHandlerParams = {
                // message status change
                onMessageReceived: function (channel, message) {
                    logger.info('Thread | useHandleChannelEvents: onMessageReceived', { channel: channel, message: message });
                    onMessageReceived(channel, message);
                },
                onMessageUpdated: function (channel, message) {
                    logger.info('Thread | useHandleChannelEvents: onMessageUpdated', { channel: channel, message: message });
                    onMessageUpdated(channel, message);
                },
                onMessageDeleted: function (channel, messageId) {
                    logger.info('Thread | useHandleChannelEvents: onMessageDeleted', { channel: channel, messageId: messageId });
                    onMessageDeleted(channel, messageId);
                },
                onReactionUpdated: function (channel, reactionEvent) {
                    logger.info('Thread | useHandleChannelEvents: onReactionUpdated', { channel: channel, reactionEvent: reactionEvent });
                    onReactionUpdated(reactionEvent);
                },
                // user status change
                onUserMuted: function (channel, user) {
                    logger.info('Thread | useHandleChannelEvents: onUserMuted', { channel: channel, user: user });
                    onUserMuted(channel, user);
                },
                onUserUnmuted: function (channel, user) {
                    logger.info('Thread | useHandleChannelEvents: onUserUnmuted', { channel: channel, user: user });
                    onUserUnmuted(channel, user);
                },
                onUserBanned: function (channel, user) {
                    logger.info('Thread | useHandleChannelEvents: onUserBanned', { channel: channel, user: user });
                    onUserBanned();
                },
                onUserUnbanned: function (channel, user) {
                    logger.info('Thread | useHandleChannelEvents: onUserUnbanned', { channel: channel, user: user });
                    onUserUnbanned();
                },
                onUserLeft: function (channel, user) {
                    logger.info('Thread | useHandleChannelEvents: onUserLeft', { channel: channel, user: user });
                    onUserLeft();
                },
                // channel status change
                onChannelFrozen: function (channel) {
                    logger.info('Thread | useHandleChannelEvents: onChannelFrozen', { channel: channel });
                    onChannelFrozen();
                },
                onChannelUnfrozen: function (channel) {
                    logger.info('Thread | useHandleChannelEvents: onChannelUnfrozen', { channel: channel });
                    onChannelUnfrozen();
                },
                onOperatorUpdated: function (channel, users) {
                    logger.info('Thread | useHandleChannelEvents: onOperatorUpdated', { channel: channel, users: users });
                    onOperatorUpdated(channel);
                },
                onTypingStatusUpdated: function (channel) {
                    if (compareIds.compareIds(channel === null || channel === void 0 ? void 0 : channel.url, currentChannel.url)) {
                        logger.info('Channel | onTypingStatusUpdated', { channel: channel });
                        var typingMembers = channel.getTypingUsers();
                        onTypingStatusUpdated(channel, typingMembers);
                    }
                },
            };
            var channelHandler = new groupChannel.GroupChannelHandler(channelHandlerParams);
            (_c = (_b = sdk.groupChannel).addGroupChannelHandler) === null || _c === void 0 ? void 0 : _c.call(_b, handlerId, channelHandler);
            logger.info('Thread | useHandleChannelEvents: Added channelHandler in Thread', { handlerId: handlerId, channelHandler: channelHandler });
        }
        return function () {
            var _a, _b, _c;
            // validation check
            if (handlerId && ((_a = sdk === null || sdk === void 0 ? void 0 : sdk.groupChannel) === null || _a === void 0 ? void 0 : _a.removeGroupChannelHandler)) {
                (_c = (_b = sdk.groupChannel).removeGroupChannelHandler) === null || _c === void 0 ? void 0 : _c.call(_b, handlerId);
                logger.info('Thread | useHandleChannelEvents: Removed channelHandler in Thread.', handlerId);
            }
        };
    }, [
        sdk === null || sdk === void 0 ? void 0 : sdk.groupChannel,
        currentChannel,
    ]);
}

function useSetCurrentUserId(_a) {
    var user = _a.user;
    var setCurrentUserId = useThread().actions.setCurrentUserId;
    React.useEffect(function () {
        setCurrentUserId(user === null || user === void 0 ? void 0 : user.userId);
    }, [user === null || user === void 0 ? void 0 : user.userId]);
}

var initialState = {
    channelUrl: '',
    message: null,
    onHeaderActionClick: undefined,
    onMoveToParentMessage: undefined,
    onBeforeSendUserMessage: undefined,
    onBeforeSendFileMessage: undefined,
    onBeforeSendVoiceMessage: undefined,
    onBeforeSendMultipleFilesMessage: undefined,
    onBeforeDownloadFileMessage: undefined,
    isMultipleFilesMessageEnabled: undefined,
    filterEmojiCategoryIds: undefined,
    currentChannel: null,
    allThreadMessages: [],
    localThreadMessages: [],
    parentMessage: null,
    channelState: Thread_context_types.ChannelStateTypes.NIL,
    parentMessageState: Thread_context_types.ParentMessageStateTypes.NIL,
    threadListState: Thread_context_types.ThreadListStateTypes.NIL,
    hasMorePrev: false,
    hasMoreNext: false,
    emojiContainer: {},
    isMuted: false,
    isChannelFrozen: false,
    currentUserId: '',
    typingMembers: [],
    nicknamesMap: null,
};
var ThreadContext = React__default.default.createContext(null);
var InternalThreadProvider = function (_a) {
    var children = _a.children;
    var storeRef = React.useRef(SendbirdContext.createStore(initialState));
    return (React__default.default.createElement(ThreadContext.Provider, { value: storeRef.current }, children));
};
var ThreadManager = function (props) {
    var message = props.message, channelUrl = props.channelUrl, onHeaderActionClick = props.onHeaderActionClick, onMoveToParentMessage = props.onMoveToParentMessage, onBeforeSendUserMessage = props.onBeforeSendUserMessage, onBeforeSendFileMessage = props.onBeforeSendFileMessage, onBeforeSendVoiceMessage = props.onBeforeSendVoiceMessage, onBeforeSendMultipleFilesMessage = props.onBeforeSendMultipleFilesMessage, onBeforeDownloadFileMessage = props.onBeforeDownloadFileMessage, isMultipleFilesMessageEnabled = props.isMultipleFilesMessageEnabled, filterEmojiCategoryIds = props.filterEmojiCategoryIds;
    var _a = useThread(), _b = _a.state, currentChannel = _b.currentChannel, parentMessage = _b.parentMessage, initializeThreadFetcher = _a.actions.initializeThreadFetcher;
    var updateState = useThreadStore().updateState;
    var propsParentMessage = useSendMultipleFilesMessage.getParentMessageFrom(message);
    // Context from SendbirdProvider
    var _c = useSendbird.useSendbird().state, stores = _c.stores, config = _c.config;
    // // stores
    var sdkStore = stores.sdkStore, userStore = stores.userStore;
    var sdk = sdkStore.sdk;
    var user = userStore.user;
    var sdkInit = sdkStore === null || sdkStore === void 0 ? void 0 : sdkStore.initialized;
    // // config
    var logger = config.logger, pubSub = config.pubSub;
    // Initialization
    useSetCurrentUserId({ user: user });
    useGetChannel({
        channelUrl: channelUrl,
        sdkInit: sdkInit,
        message: message,
    }, { sdk: sdk, logger: logger });
    useGetParentMessage({
        channelUrl: channelUrl,
        sdkInit: sdkInit,
        parentMessage: propsParentMessage,
    }, { sdk: sdk, logger: logger });
    useGetAllEmoji({ sdk: sdk }, { logger: logger });
    // Handle channel events
    useHandleChannelEvents({
        sdk: sdk,
        currentChannel: currentChannel,
    }, { logger: logger });
    useHandleThreadPubsubEvents({
        sdkInit: sdkInit,
        currentChannel: currentChannel,
        parentMessage: parentMessage,
    }, { logger: logger, pubSub: pubSub });
    React.useEffect(function () {
        if (stores.sdkStore.initialized && config.isOnline) {
            initializeThreadFetcher();
        }
    }, [stores.sdkStore.initialized, config.isOnline, initializeThreadFetcher]);
    // memo
    var nicknamesMap = React.useMemo(function () { return ((config.groupChannel.replyType !== 'none' && currentChannel)
        ? useSendMultipleFilesMessage.getNicknamesMapFromMembers(currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.members)
        : new Map()); }, [currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.members]);
    useDeepCompareEffect.useDeepCompareEffect(function () {
        updateState({
            channelUrl: channelUrl,
            message: message,
            onHeaderActionClick: onHeaderActionClick,
            onMoveToParentMessage: onMoveToParentMessage,
            onBeforeSendUserMessage: onBeforeSendUserMessage,
            onBeforeSendFileMessage: onBeforeSendFileMessage,
            onBeforeSendVoiceMessage: onBeforeSendVoiceMessage,
            onBeforeSendMultipleFilesMessage: onBeforeSendMultipleFilesMessage,
            onBeforeDownloadFileMessage: onBeforeDownloadFileMessage,
            isMultipleFilesMessageEnabled: isMultipleFilesMessageEnabled,
            filterEmojiCategoryIds: filterEmojiCategoryIds,
            nicknamesMap: nicknamesMap,
        });
    }, [
        channelUrl,
        message,
        onHeaderActionClick,
        onMoveToParentMessage,
        onBeforeSendUserMessage,
        onBeforeSendFileMessage,
        onBeforeSendVoiceMessage,
        onBeforeSendMultipleFilesMessage,
        onBeforeDownloadFileMessage,
        isMultipleFilesMessageEnabled,
        filterEmojiCategoryIds,
        nicknamesMap,
    ]);
    return null;
};
var ThreadProvider = function (props) {
    var children = props.children;
    return (React__default.default.createElement(InternalThreadProvider, null,
        React__default.default.createElement(ThreadManager, _tslib.__assign({}, props)),
        React__default.default.createElement(UserProfileContext.UserProfileProvider, _tslib.__assign({}, props), children)));
};
var useThreadContext = function () {
    var _a = useThread(), state = _a.state, actions = _a.actions;
    return _tslib.__assign(_tslib.__assign({}, state), actions);
};
var useThreadStore = function () {
    return SendbirdContext.useStore(ThreadContext, function (state) { return state; }, initialState);
};

exports.InternalThreadProvider = InternalThreadProvider;
exports.ThreadContext = ThreadContext;
exports.ThreadManager = ThreadManager;
exports.ThreadProvider = ThreadProvider;
exports.useThread = useThread;
exports.useThreadContext = useThreadContext;
//# sourceMappingURL=bundle-B7URG8PR.js.map
