"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 types_1 = require("@selfcommunity/types");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const system_1 = require("@mui/system");
const notistack_1 = require("notistack");
const react_intl_1 = require("react-intl");
const lab_1 = require("@mui/lab");
const utils_1 = require("@selfcommunity/utils");
const Errors_1 = require("../../constants/Errors");
const errors_1 = require("../../utils/errors");
const react_core_1 = require("@selfcommunity/react-core");
const PREFIX = 'SCFriendshipUserButton';
const classes = {
    root: `${PREFIX}-root`
};
const Root = (0, styles_1.styled)(lab_1.LoadingButton, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(() => ({}));
// TODO: fix component
/**
 * > API documentation for the Community-JS Friendship User Button component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

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

 * @param inProps
 */
function FriendshipUserButton(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className, userId, user } = props, rest = tslib_1.__rest(props, ["className", "userId", "user"]);
    // CONTEXT
    const scContext = (0, react_core_1.useSCContext)();
    const scUserContext = (0, react_1.useContext)(react_core_1.SCUserContext);
    const scConnectionsManager = scUserContext.managers.connections;
    const { enqueueSnackbar } = (0, notistack_1.useSnackbar)();
    // STATE
    const { scUser } = (0, react_core_1.useSCFetchUser)({ id: userId, user });
    const [status, setStatus] = (0, react_1.useState)(null);
    const [disabled, setDisabled] = (0, react_1.useState)(false);
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    /**
     * Handle actions
     */
    const handleConnectionStatus = () => {
        if (!scUserContext.user) {
            scContext.settings.handleAnonymousAction();
        }
        else if (react_core_1.UserUtils.isBlocked(scUserContext.user)) {
            enqueueSnackbar((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.common.userBlocked", defaultMessage: "ui.common.userBlocked" }), {
                variant: 'warning',
                autoHideDuration: 3000
            });
        }
        else {
            let _action;
            if (status === types_1.SCConnectionStatus.CONNECTED) {
                _action = scConnectionsManager.removeConnection;
            }
            else if (status === types_1.SCConnectionStatus.CONNECTION_REQUEST_SENT) {
                _action = scConnectionsManager.cancelRequestConnection;
            }
            else if (status === types_1.SCConnectionStatus.CONNECTION_REQUEST_RECEIVED) {
                _action = scConnectionsManager.acceptConnection;
            }
            else if (status === null) {
                _action = scConnectionsManager.requestConnection;
            }
            _action(scUser).catch((e) => {
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
                if ((0, errors_1.catchUnauthorizedActionByBlockedUser)(e, scUserContext.managers.blockedUsers.isBlocked(scUser), enqueueSnackbar)) {
                    setDisabled(true);
                }
                else {
                    enqueueSnackbar((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.common.actionToUserDeleted", defaultMessage: "ui.common.actionToUserDeleted" }), {
                        variant: 'warning',
                        autoHideDuration: 3000
                    });
                }
            });
        }
    };
    /**
     * Get current translated status
     */
    const getStatus = () => {
        let _status;
        switch (status) {
            case types_1.SCConnectionStatus.CONNECTED:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.friendshipUserButton.removeConnection", id: "ui.friendshipUserButton.removeConnection" });
                break;
            case types_1.SCConnectionStatus.CONNECTION_REQUEST_SENT:
                _status = ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.friendshipUserButton.cancelConnectionRequest", id: "ui.friendshipUserButton.cancelConnectionRequest" }));
                break;
            case types_1.SCConnectionStatus.CONNECTION_REQUEST_RECEIVED:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.friendshipUserButton.acceptConnection", id: "ui.friendshipUserButton.acceptConnection" });
                break;
            default:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.friendshipUserButton.requestConnection", id: "ui.friendshipUserButton.requestConnection" });
                break;
        }
        return _status;
    };
    (0, react_1.useEffect)(() => {
        /**
         * Call scConnectionsManager.isFollowed inside an effect
         * to avoid warning rendering child during update parent state
         */
        if (authUserId && authUserId !== scUser.id) {
            const _status = scConnectionsManager.status(scUser);
            setStatus(_status);
        }
    }, [authUserId, scConnectionsManager.status]);
    // same user
    if (scUserContext.user && scUserContext.user.id === scUser.id) {
        return null;
    }
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ size: "small", variant: "outlined", disabled: disabled, loading: scUserContext.user ? scConnectionsManager.isLoading(scUser) : null, onClick: handleConnectionStatus, className: (0, classnames_1.default)(classes.root, className) }, rest, { children: getStatus() })));
}
exports.default = FriendshipUserButton;
