"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const styles_1 = require("@mui/material/styles");
const utils_1 = require("@selfcommunity/utils");
const react_core_1 = require("@selfcommunity/react-core");
const types_1 = require("@selfcommunity/types");
const lab_1 = require("@mui/lab");
const react_intl_1 = require("react-intl");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const system_1 = require("@mui/system");
const Errors_1 = require("../../constants/Errors");
const PubSub_1 = require("../../constants/PubSub");
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const PREFIX = 'SCGroupSubscribeButton';
const classes = {
    root: `${PREFIX}-root`
};
const Root = (0, styles_1.styled)(lab_1.LoadingButton, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({}));
/**
 * > API documentation for the Community-JS Group Subscribe Button component. Learn about the available props and the CSS API.

 #### Import

 ```jsx
 import {GroupSubscribeButton} from '@selfcommunity/react-ui';
 ```

 #### Component Name

 The name `SCGroupSubscribeButton` can be used when providing style overrides in the theme.


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCGroupSubscribeButton-root|Styles applied to the root element.|

 * @param inProps
 */
function GroupSubscribeButton(inProps) {
    var _a;
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className, groupId, group, user, onSubscribe } = props, rest = tslib_1.__rest(props, ["className", "groupId", "group", "user", "onSubscribe"]);
    // STATE
    const [status, setStatus] = (0, react_1.useState)(null);
    // CONTEXT
    const scContext = (0, react_core_1.useSCContext)();
    const scUserContext = (0, react_core_1.useSCUser)();
    const scGroupsManager = scUserContext.managers.groups;
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    const { scGroup } = (0, react_core_1.useSCFetchGroup)({
        id: groupId,
        group,
        cacheStrategy: authUserId ? utils_1.CacheStrategies.CACHE_FIRST : utils_1.CacheStrategies.STALE_WHILE_REVALIDATE
    });
    const isGroupAdmin = (0, react_1.useMemo)(() => { var _a; return scUserContext.user && ((_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id) === scUserContext.user.id; }, [scUserContext.user, (_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id]);
    (0, react_1.useEffect)(() => {
        /**
         * Call scGroupsManager.subscriptionStatus inside an effect
         * to avoid warning rendering child during update parent state
         */
        if (authUserId) {
            setStatus(scGroupsManager.subscriptionStatus(scGroup));
        }
    }, [authUserId, scGroupsManager.subscriptionStatus, scGroup]);
    /**
     * Notify UI when a member is added to a group
     * @param group
     * @param user
     */
    function notifyChanges(group, user) {
        if (group && user) {
            pubsub_js_1.default.publish(`${PubSub_1.SCTopicType.GROUP}.${PubSub_1.SCGroupEventType.ADD_MEMBER}`, { group, user });
        }
    }
    const subscribe = (user) => {
        scGroupsManager
            .subscribe(scGroup, user === null || user === void 0 ? void 0 : user.id)
            .then(() => {
            const _status = scGroup.privacy === types_1.SCGroupPrivacyType.PRIVATE && scGroup.subscription_status !== types_1.SCGroupSubscriptionStatusType.INVITED
                ? types_1.SCGroupSubscriptionStatusType.REQUESTED
                : types_1.SCGroupSubscriptionStatusType.SUBSCRIBED;
            notifyChanges(scGroup, user);
            onSubscribe && onSubscribe(scGroup, _status);
        })
            .catch((e) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
        });
    };
    const unsubscribe = () => {
        scGroupsManager
            .unsubscribe(scGroup)
            .then(() => {
            onSubscribe && onSubscribe(scGroup, null);
        })
            .catch((e) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
        });
    };
    const handleSubscribeAction = () => {
        if (!scUserContext.user) {
            scContext.settings.handleAnonymousAction();
        }
        else {
            status === types_1.SCGroupSubscriptionStatusType.SUBSCRIBED && !(user === null || user === void 0 ? void 0 : user.id) ? unsubscribe() : (user === null || user === void 0 ? void 0 : user.id) ? subscribe(user) : subscribe();
        }
    };
    /**
     * Get current translated status
     */
    const getStatus = (0, react_1.useMemo)(() => {
        let _status;
        switch (status) {
            case types_1.SCGroupSubscriptionStatusType.REQUESTED:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.groupSubscribeButton.waitingApproval", id: "ui.groupSubscribeButton.waitingApproval" });
                break;
            case types_1.SCGroupSubscriptionStatusType.SUBSCRIBED:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.groupSubscribeButton.exit", id: "ui.groupSubscribeButton.exit" });
                break;
            case types_1.SCGroupSubscriptionStatusType.INVITED:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.groupSubscribeButton.accept", id: "ui.groupSubscribeButton.accept" });
                break;
            default:
                scGroup.privacy === types_1.SCGroupPrivacyType.PUBLIC
                    ? (_status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.groupSubscribeButton.enter", id: "ui.groupSubscribeButton.enter" }))
                    : (_status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.groupSubscribeButton.requestAccess", id: "ui.groupSubscribeButton.requestAccess" }));
                break;
        }
        return _status;
    }, [status, scGroup]);
    if (!scGroup || (isGroupAdmin && (user === null || user === void 0 ? void 0 : user.id) === scUserContext.user.id) || (isGroupAdmin && !(user === null || user === void 0 ? void 0 : user.id))) {
        return null;
    }
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ size: "small", variant: "outlined", onClick: handleSubscribeAction, loading: scUserContext.user ? scGroupsManager.isLoading(scGroup) : null, disabled: status === types_1.SCGroupSubscriptionStatusType.REQUESTED, className: (0, classnames_1.default)(classes.root, className) }, rest, { children: isGroupAdmin ? (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.groupSubscribeButton.accept", id: "ui.groupSubscribeButton.accept" }) : getStatus })));
}
exports.default = GroupSubscribeButton;
