'use strict';

var _tslib = require('./bundle-CxoFSSXv.js');
var SendbirdContext = require('./bundle-AAO7jUU2.js');
var React = require('react');
var groupChannel = require('@sendbird/chat/groupChannel');
var uuid = require('./bundle-BUGwK1WK.js');
var compareIds = require('./bundle-CvQwksvR.js');
var utils = require('./bundle-DQNu-S6D.js');
var UserProfileContext = require('./bundle-DeyX1dvY.js');
var useSendbird = require('./bundle-LI9JjqG2.js');

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

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

function useSetChannel(_a) {
    var _this = this;
    var channelUrl = _a.channelUrl, sdk = _a.sdk, logger = _a.logger, initialized = _a.initialized, _b = _a.dependencies, dependencies = _b === void 0 ? [] : _b;
    var _c = useChannelSettings().actions, setChannel = _c.setChannel, setInvalid = _c.setInvalid, setLoading = _c.setLoading;
    React.useEffect(function () {
        var controller = new AbortController();
        var signal = controller.signal;
        var fetchChannel = function () { return _tslib.__awaiter(_this, void 0, void 0, function () {
            var groupChannel, error_1;
            return _tslib.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, 3, 4]);
                        if (!channelUrl) {
                            logger.warning('ChannelSettings: channel url is required');
                            setLoading(false);
                            return [2 /*return*/];
                        }
                        if (!initialized || !sdk) {
                            logger.warning('ChannelSettings: SDK is not initialized');
                            setLoading(false);
                            return [2 /*return*/];
                        }
                        if (!sdk.groupChannel) {
                            logger.warning('ChannelSettings: GroupChannelModule is not specified in the SDK');
                            setLoading(false);
                            return [2 /*return*/];
                        }
                        setLoading(true);
                        return [4 /*yield*/, sdk.groupChannel.getChannel(channelUrl)];
                    case 1:
                        groupChannel = _a.sent();
                        if (!signal.aborted) {
                            logger.info('ChannelSettings | useSetChannel: fetched group channel', groupChannel);
                            setChannel(groupChannel);
                        }
                        return [3 /*break*/, 4];
                    case 2:
                        error_1 = _a.sent();
                        if (!signal.aborted) {
                            logger.error('ChannelSettings | useSetChannel: failed fetching channel', error_1);
                            setInvalid(true);
                        }
                        return [3 /*break*/, 4];
                    case 3:
                        if (!signal.aborted) {
                            setLoading(false);
                        }
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        fetchChannel();
        return function () { return controller.abort(); }; // Cleanup with AbortController
    }, _tslib.__spreadArray([channelUrl, initialized, sdk], dependencies, true));
}

var useChannelHandler = function (_a) {
    var sdk = _a.sdk, channelUrl = _a.channelUrl, logger = _a.logger, forceUpdateUI = _a.forceUpdateUI, _b = _a.dependencies, dependencies = _b === void 0 ? [] : _b;
    React.useEffect(function () {
        if (!sdk || !sdk.groupChannel) {
            logger.warning('ChannelSettings: SDK or GroupChannelModule is not available');
            return;
        }
        var newChannelHandlerId = uuid.uuidv4();
        var channelHandler = new groupChannel.GroupChannelHandler({
            onUserLeft: function (channel, user) {
                if (compareIds.compareIds(channel === null || channel === void 0 ? void 0 : channel.url, channelUrl)) {
                    logger.info('ChannelSettings: onUserLeft', { channel: channel, user: user });
                    forceUpdateUI();
                }
            },
            onUserBanned: function (channel, user) {
                if (compareIds.compareIds(channel === null || channel === void 0 ? void 0 : channel.url, channelUrl) && channel.isGroupChannel()) {
                    logger.info('ChannelSettings: onUserBanned', { channel: channel, user: user });
                    forceUpdateUI();
                }
            },
        });
        sdk.groupChannel.addGroupChannelHandler(newChannelHandlerId, channelHandler);
        return function () {
            if (sdk.groupChannel && newChannelHandlerId) {
                logger.info('ChannelSettings: Removing message receiver handler', newChannelHandlerId);
                sdk.groupChannel.removeGroupChannelHandler(newChannelHandlerId);
            }
        };
    }, _tslib.__spreadArray([sdk, channelUrl, logger], dependencies, true));
    return null;
};

var ChannelSettingsContext = React.createContext(null);
var initialState = {
    // Props
    channelUrl: '',
    onCloseClick: undefined,
    onLeaveChannel: undefined,
    onChannelModified: undefined,
    onBeforeUpdateChannel: undefined,
    renderUserListItem: undefined,
    queries: {},
    overrideInviteUser: undefined,
    // Managed states
    channel: null,
    loading: false,
    invalidChannel: false,
    forceUpdateUI: function () { },
    setChannelUpdateId: function () { },
};
/**
 * @returns {ReturnType<typeof createStore<ChannelSettingsState>>}
 */
var useChannelSettingsStore = function () {
    return SendbirdContext.useStore(ChannelSettingsContext, function (state) { return state; }, initialState);
};
var ChannelSettingsManager = function (_a) {
    var _b;
    var channelUrl = _a.channelUrl, onCloseClick = _a.onCloseClick, onLeaveChannel = _a.onLeaveChannel, onChannelModified = _a.onChannelModified, overrideInviteUser = _a.overrideInviteUser, onBeforeUpdateChannel = _a.onBeforeUpdateChannel, queries = _a.queries, renderUserListItem = _a.renderUserListItem;
    var state = useSendbird.useSendbird().state;
    var config = state.config, stores = state.stores;
    var updateState = useChannelSettingsStore().updateState;
    var logger = config.logger;
    var _c = (_b = stores === null || stores === void 0 ? void 0 : stores.sdkStore) !== null && _b !== void 0 ? _b : {}, sdk = _c.sdk, initialized = _c.initialized;
    var _d = React.useState(function () { return uuid.uuidv4(); }), channelUpdateId = _d[0], setChannelUpdateId = _d[1];
    var forceUpdateUI = React.useCallback(function () { return setChannelUpdateId(uuid.uuidv4()); }, []);
    var dependencies = [channelUpdateId];
    useSetChannel({
        channelUrl: channelUrl,
        sdk: sdk,
        logger: logger,
        initialized: initialized,
        dependencies: dependencies,
    });
    useChannelHandler({
        sdk: sdk,
        channelUrl: channelUrl,
        logger: logger,
        forceUpdateUI: forceUpdateUI,
        dependencies: dependencies,
    });
    React.useEffect(function () {
        updateState({
            channelUrl: channelUrl,
            onCloseClick: onCloseClick,
            onLeaveChannel: onLeaveChannel,
            onChannelModified: onChannelModified,
            onBeforeUpdateChannel: onBeforeUpdateChannel,
            renderUserListItem: renderUserListItem,
            queries: queries,
            overrideInviteUser: overrideInviteUser,
            forceUpdateUI: forceUpdateUI,
            setChannelUpdateId: setChannelUpdateId,
        });
    }, [
        channelUrl,
        onCloseClick,
        onLeaveChannel,
        onChannelModified,
        onBeforeUpdateChannel,
        renderUserListItem,
        queries,
        overrideInviteUser,
        forceUpdateUI,
    ]);
    return null;
};
var createChannelSettingsStore = function () { return SendbirdContext.createStore(initialState); };
var InternalChannelSettingsProvider = function (_a) {
    var children = _a.children;
    var storeRef = React.useRef(createChannelSettingsStore());
    return (React__default.default.createElement(ChannelSettingsContext.Provider, { value: storeRef.current }, children));
};
var ChannelSettingsProvider = function (props) {
    var children = props.children, className = props.className;
    return (React__default.default.createElement(InternalChannelSettingsProvider, null,
        React__default.default.createElement(ChannelSettingsManager, _tslib.__assign({}, props)),
        React__default.default.createElement(UserProfileContext.UserProfileProvider, _tslib.__assign({}, props),
            React__default.default.createElement("div", { className: utils.classnames('sendbird-channel-settings', className) }, children))));
};
var useChannelSettingsContext = function () {
    var _a = useChannelSettings(), state = _a.state, actions = _a.actions;
    return _tslib.__assign(_tslib.__assign({}, state), actions);
};

var useChannelSettings = function () {
    var store = React.useContext(ChannelSettingsContext);
    if (!store)
        throw new Error('useChannelSettings must be used within a ChannelSettingsProvider');
    var state = SendbirdContext.shimExports.useSyncExternalStore(store.subscribe, store.getState);
    var actions = React.useMemo(function () { return ({
        setChannel: function (channel) { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { channel: channel })); }); },
        setLoading: function (loading) { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { loading: loading })); }); },
        setInvalid: function (invalid) { return store.setState(function (state) { return (_tslib.__assign(_tslib.__assign({}, state), { invalidChannel: invalid })); }); },
    }); }, [store]);
    return { state: state, actions: actions };
};

exports.ChannelSettingsProvider = ChannelSettingsProvider;
exports.useChannelSettings = useChannelSettings;
exports.useChannelSettingsContext = useChannelSettingsContext;
//# sourceMappingURL=bundle-CcVLRLk8.js.map
