'use strict';

var _tslib = require('./bundle-CxoFSSXv.js');
var React = require('react');
var groupChannel = require('@sendbird/chat/groupChannel');
var uikitTools = require('@sendbird/uikit-tools');
var UserProfileContext = require('./bundle-DeyX1dvY.js');
var useMarkAsDeliveredScheduler = require('./bundle-ys65nyET.js');
var SendbirdContext = require('./bundle-AAO7jUU2.js');
var utils = require('./bundle-DQNu-S6D.js');
var useSendbird = require('./bundle-LI9JjqG2.js');
var useDeepCompareEffect = require('./bundle-ChpcAmBg.js');

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

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

var useGroupChannelList = function () {
    var store = React.useContext(GroupChannelListContext);
    if (!store)
        throw new Error('useGroupChannelList must be used within a GroupChannelListProvider');
    var setGroupChannels = React.useCallback(function (channels) {
        store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { groupChannels: channels })); }, true);
    }, []);
    var state = SendbirdContext.shimExports.useSyncExternalStore(store.subscribe, store.getState);
    var actions = React.useMemo(function () { return ({
        setGroupChannels: setGroupChannels,
    }); }, [setGroupChannels]);
    return { state: state, actions: actions };
};

var GroupChannelListContext = React__default.default.createContext(null);
var initialState = {
    className: '',
    selectedChannelUrl: '',
    disableAutoSelect: false,
    allowProfileEdit: false,
    isTypingIndicatorEnabled: false,
    isMessageReceiptStatusEnabled: false,
    onChannelSelect: function () { },
    onChannelCreated: function () { },
    onThemeChange: utils.noop,
    onCreateChannelClick: utils.noop,
    onBeforeCreateChannel: null,
    onUserProfileUpdated: utils.noop,
    typingChannelUrls: [],
    refreshing: false,
    initialized: false,
    groupChannels: [],
    refresh: null,
    loadMore: null,
    scrollRef: { current: null },
};
/**
 * @returns {ReturnType<typeof createStore<GroupChannelListState>>}
 */
var useGroupChannelListStore = function () {
    return SendbirdContext.useStore(GroupChannelListContext, function (state) { return state; }, initialState);
};
var GroupChannelListManager = function (_a) {
    var _b, _c, _d, _e, _f, _g;
    var _h = _a.className, className = _h === void 0 ? '' : _h, _j = _a.selectedChannelUrl, selectedChannelUrl = _j === void 0 ? '' : _j, _k = _a.disableAutoSelect, disableAutoSelect = _k === void 0 ? false : _k, channelListQueryParams = _a.channelListQueryParams, onThemeChange = _a.onThemeChange, onChannelSelect = _a.onChannelSelect, onChannelCreated = _a.onChannelCreated, onCreateChannelClick = _a.onCreateChannelClick, onBeforeCreateChannel = _a.onBeforeCreateChannel, onUserProfileUpdated = _a.onUserProfileUpdated, props = _tslib.__rest(_a, ["className", "selectedChannelUrl", "disableAutoSelect", "channelListQueryParams", "onThemeChange", "onChannelSelect", "onChannelCreated", "onCreateChannelClick", "onBeforeCreateChannel", "onUserProfileUpdated"]);
    var sendbirdState = useSendbird.useSendbird().state;
    var config = sendbirdState.config, stores = sendbirdState.stores;
    var _l = useGroupChannelList(), state = _l.state, actions = _l.actions;
    var updateState = useGroupChannelListStore().updateState;
    var sdkStore = stores.sdkStore;
    var sdk = sdkStore.sdk;
    var isConnected = useMarkAsDeliveredScheduler.useOnlineStatus(sdk, config.logger);
    var scheduler = useMarkAsDeliveredScheduler.useMarkAsDeliveredScheduler({ isConnected: isConnected }, config);
    var scrollRef = React.useRef(null);
    var channelListDataSource = uikitTools.useGroupChannelList(sdk, {
        collectionCreator: getCollectionCreator(sdk, channelListQueryParams),
        markAsDelivered: function (channels) { return channels.forEach(scheduler.push); },
        onChannelsDeleted: function (channelUrls) {
            channelUrls.forEach(function (url) {
                if (url === selectedChannelUrl)
                    onChannelSelect(null);
            });
        },
        onChannelsUpdated: function () {
            actions.setGroupChannels(groupChannels);
        },
    });
    var refreshing = channelListDataSource.refreshing, initialized = channelListDataSource.initialized, groupChannels = channelListDataSource.groupChannels, refresh = channelListDataSource.refresh, loadMore = channelListDataSource.loadMore;
    // SideEffect: Auto select channel
    React.useEffect(function () {
        var _a;
        if (!disableAutoSelect && stores.sdkStore.initialized && initialized) {
            if (!selectedChannelUrl)
                onChannelSelect((_a = groupChannels[0]) !== null && _a !== void 0 ? _a : null);
        }
    }, [disableAutoSelect, stores.sdkStore.initialized, initialized, selectedChannelUrl]);
    // Recreates the GroupChannelCollection when `channelListQueryParams` change
    React.useEffect(function () {
        refresh === null || refresh === void 0 ? void 0 : refresh();
    }, [
        Object.keys(channelListQueryParams !== null && channelListQueryParams !== void 0 ? channelListQueryParams : {}).sort()
            .map(function (key) { return "".concat(key, "=").concat(encodeURIComponent(JSON.stringify(channelListQueryParams[key]))); })
            .join('&'),
    ]);
    var typingChannelUrls = state.typingChannelUrls;
    uikitTools.useGroupChannelHandler(sdk, {
        onTypingStatusUpdated: function (channel) {
            var _a;
            var channelList = typingChannelUrls.filter(function (channelUrl) { return channelUrl !== channel.url; });
            if (((_a = channel.getTypingUsers()) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                updateState({
                    typingChannelUrls: (channelList.concat(channel.url)),
                });
            }
            else {
                updateState({
                    typingChannelUrls: (channelList),
                });
            }
        },
    });
    var allowProfileEdit = (_c = (_b = props.allowProfileEdit) !== null && _b !== void 0 ? _b : config.allowProfileEdit) !== null && _c !== void 0 ? _c : true;
    var isTypingIndicatorEnabled = (_e = (_d = props.isTypingIndicatorEnabled) !== null && _d !== void 0 ? _d : config.groupChannelList.enableTypingIndicator) !== null && _e !== void 0 ? _e : false;
    var isMessageReceiptStatusEnabled = (_g = (_f = props.isMessageReceiptStatusEnabled) !== null && _f !== void 0 ? _f : config.groupChannelList.enableMessageReceiptStatus) !== null && _g !== void 0 ? _g : false;
    var eventHandlers = React.useMemo(function () { return ({
        onChannelSelect: onChannelSelect,
        onChannelCreated: onChannelCreated,
        onThemeChange: onThemeChange,
        onCreateChannelClick: onCreateChannelClick,
        onBeforeCreateChannel: onBeforeCreateChannel,
        onUserProfileUpdated: onUserProfileUpdated,
    }); }, [
        onChannelSelect,
        onChannelCreated,
        onThemeChange,
        onCreateChannelClick,
        onBeforeCreateChannel,
        onUserProfileUpdated,
    ]);
    var configurations = React.useMemo(function () { return ({
        className: className,
        selectedChannelUrl: selectedChannelUrl,
        disableAutoSelect: disableAutoSelect,
        allowProfileEdit: allowProfileEdit,
        isTypingIndicatorEnabled: isTypingIndicatorEnabled,
        isMessageReceiptStatusEnabled: isMessageReceiptStatusEnabled,
        typingChannelUrls: typingChannelUrls,
        refreshing: refreshing,
        initialized: initialized,
        refresh: refresh,
        loadMore: loadMore,
    }); }, [
        className,
        selectedChannelUrl,
        disableAutoSelect,
        allowProfileEdit,
        isTypingIndicatorEnabled,
        isMessageReceiptStatusEnabled,
        typingChannelUrls,
        refreshing,
        initialized,
        scrollRef,
    ]);
    useDeepCompareEffect.useDeepCompareEffect(function () {
        updateState(_tslib.__assign(_tslib.__assign(_tslib.__assign({}, eventHandlers), configurations), { groupChannels: groupChannels }));
    }, [
        configurations,
        eventHandlers,
        groupChannels.map(function (groupChannel) { return groupChannel.serialize(); }),
    ]);
    return null;
};
var createGroupChannelListStore = function () { return SendbirdContext.createStore(initialState); };
var InternalGroupChannelListProvider = function (_a) {
    var children = _a.children;
    var storeRef = React.useRef(createGroupChannelListStore());
    return (React__default.default.createElement(GroupChannelListContext.Provider, { value: storeRef.current }, children));
};
var GroupChannelListProvider = function (props) {
    var children = props.children, className = props.className;
    return (React__default.default.createElement(InternalGroupChannelListProvider, null,
        React__default.default.createElement(GroupChannelListManager, _tslib.__assign({}, props)),
        React__default.default.createElement(UserProfileContext.UserProfileProvider, _tslib.__assign({}, props),
            React__default.default.createElement("div", { className: "sendbird-channel-list ".concat(className) }, children))));
};
// Keep this function for backward compatibility.
var useGroupChannelListContext = function () {
    var _a = useGroupChannelList(), state = _a.state, actions = _a.actions;
    return _tslib.__assign(_tslib.__assign({}, state), actions);
};
function getCollectionCreator(sdk, channelListQueryParams) {
    return function (defaultParams) {
        var params = _tslib.__assign(_tslib.__assign({}, defaultParams), channelListQueryParams);
        return sdk.groupChannel.createGroupChannelCollection(_tslib.__assign(_tslib.__assign({}, params), { filter: new groupChannel.GroupChannelFilter(params) }));
    };
}

exports.GroupChannelListContext = GroupChannelListContext;
exports.GroupChannelListManager = GroupChannelListManager;
exports.GroupChannelListProvider = GroupChannelListProvider;
exports.useGroupChannelList = useGroupChannelList;
exports.useGroupChannelListContext = useGroupChannelListContext;
exports.useGroupChannelListStore = useGroupChannelListStore;
//# sourceMappingURL=bundle-CpzjjrHg.js.map
