"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 react_intl_1 = require("react-intl");
const Popper_1 = tslib_1.__importDefault(require("@mui/material/Popper"));
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const notistack_1 = require("notistack");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const material_1 = require("@mui/material");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const constants_1 = require("./constants");
const ConfirmDialog_1 = tslib_1.__importDefault(require("../../../shared/ConfirmDialog/ConfirmDialog"));
const components_react_1 = require("@livekit/components-react");
const LiveStreamProvider_1 = require("./LiveStreamProvider");
const utils_1 = require("@selfcommunity/utils");
const Errors_1 = require("../../../constants/Errors");
const PREFIX = 'SCParticipantTileActionsMenu';
const classes = {
    root: `${PREFIX}-root`,
    button: `${PREFIX}-button`,
    popperRoot: `${PREFIX}-popper-root`,
    paper: `${PREFIX}-paper`,
    item: `${PREFIX}-item`,
    itemText: `${PREFIX}-item-text`,
    subItem: `${PREFIX}-sub-item`,
    subItemText: `${PREFIX}-sub-item-text`,
    footerSubItems: `${PREFIX}-footer-sub-items`,
    selectedIcon: `${PREFIX}-selected-icon`,
    sectionBadge: `${PREFIX}-section-badge`,
    sectionWithSelectionIcon: `${PREFIX}-section-with-selection-icon`,
    visibilityIcons: `${PREFIX}-visibility-icons`
};
const PopperRoot = (0, styles_1.styled)(Popper_1.default, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.popperRoot
})(() => ({
    '& .SCParticipantTileActionsMenu-paper': {
        borderRadius: 5
    }
}));
const Root = (0, styles_1.styled)(material_1.Box, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({
    display: 'inline-block',
    '& button': {
        color: theme.palette.common.white
    }
}));
function ContributionActionsMenu(props) {
    // PROPS
    const { className, participant, onBanParticipant, PopperProps = {} } = props, rest = tslib_1.__rest(props, ["className", "participant", "onBanParticipant", "PopperProps"]);
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    // CONTEXT
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    const scContext = (0, react_1.useContext)(react_core_1.SCContext);
    const scUserContext = (0, react_1.useContext)(react_core_1.SCUserContext);
    const { enqueueSnackbar } = (0, notistack_1.useSnackbar)();
    const p = (0, components_react_1.useEnsureParticipant)(participant);
    const { liveStream } = (0, LiveStreamProvider_1.useLiveStream)();
    // GENERAL POPPER STATE
    const [open, setOpen] = (0, react_1.useState)(false);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    // CONFIRM ACTION DIALOG STATE
    const [openConfirmDialog, setOpenConfirmDialog] = (0, react_1.useState)(false);
    const [currentAction, setCurrentAction] = (0, react_1.useState)(null);
    const [currentActionLoading, setCurrentActionLoading] = (0, react_1.useState)(null);
    // CONST
    let popperRef = (0, react_1.useRef)(null);
    /**
     * Handles open popup
     */
    function handleOpen() {
        if (scUserContext.user) {
            setOpen(true);
        }
        else {
            scContext.settings.handleAnonymousAction();
        }
    }
    /**
     * Closes popup
     */
    function handleClose() {
        if (popperRef.current && popperRef.current.contains(event.target)) {
            return;
        }
        setOpen(false);
        if (rest.onClose) {
            rest.onClose();
        }
    }
    /**
     * Perform ban participant
     */
    const performBanParticipant = (0, react_1.useMemo)(() => () => tslib_1.__awaiter(this, void 0, void 0, function* () {
        const res = yield api_services_1.LiveStreamApiClient.removeParticipant(liveStream.id, { participant_id: p.identity });
        if (res.status >= 300) {
            return Promise.reject(res);
        }
        return yield Promise.resolve(res.data);
    }), [p]);
    /**
     * Handle action
     */
    function handleAction(action) {
        if (action === constants_1.BAN_ROOM_USER) {
            setCurrentAction(constants_1.BAN_ROOM_USER);
            setOpenConfirmDialog(true);
            handleClose();
        }
    }
    /**
     * Perform additional operations at the end of single action
     */
    function performPostConfirmAction(success) {
        if (success) {
            setCurrentActionLoading(null);
            setCurrentAction(null);
            setOpenConfirmDialog(false);
            enqueueSnackbar((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.contributionActionMenu.actionSuccess", defaultMessage: "ui.contributionActionMenu.actionSuccess" }), {
                variant: 'success',
                autoHideDuration: 3000
            });
        }
        else {
            setCurrentActionLoading(null);
            enqueueSnackbar((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.contributionActionMenu.actionError", defaultMessage: "ui.contributionActionMenu.actionError" }), {
                variant: 'error',
                autoHideDuration: 3000
            });
        }
    }
    /**
     * Delete a contribution
     */
    function handleConfirmedAction() {
        if (p && !isLoading && !currentActionLoading) {
            if (currentAction === constants_1.BAN_ROOM_USER) {
                setCurrentActionLoading(constants_1.BAN_ROOM_USER);
                performBanParticipant()
                    .then(() => {
                    onBanParticipant && onBanParticipant(p);
                    performPostConfirmAction(true);
                })
                    .catch((error) => {
                    utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
                    performPostConfirmAction(false);
                });
            }
        }
    }
    /**
     * Can authenticated ban a user in a room
     */
    const canBanUser = (0, react_1.useMemo)(() => () => {
        return (scUserContext.user &&
            liveStream &&
            p &&
            p.identity &&
            liveStream.host.id === scUserContext.user.id &&
            scUserContext.user.id.toString() !== p.identity);
    }, [scUserContext, liveStream, p]);
    /**
     * Renders section general
     */
    function renderGeneralSection() {
        return ((0, jsx_runtime_1.jsx)(material_1.Box, { children: canBanUser() && ((0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ className: classes.subItem, disabled: currentActionLoading === constants_1.BAN_ROOM_USER }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemIcon, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "person" }) }), (0, jsx_runtime_1.jsx)(material_1.ListItemText, { primary: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.liveStreamRoom.participantTileActions.banRoomUser", defaultMessage: "ui.liveStreamRoom.participantTileActions.banRoomUser" }), onClick: () => handleAction(constants_1.BAN_ROOM_USER), classes: { root: classes.itemText } })] }))) }));
    }
    /**
     * Renders contribution menu content
     */
    function renderContent() {
        return ((0, jsx_runtime_1.jsx)(material_1.Box, { children: (0, jsx_runtime_1.jsx)(material_1.MenuList, { children: renderGeneralSection() }) }));
    }
    /**
     * Renders component only if the logged user has actions available
     */
    if (!canBanUser()) {
        return null;
    }
    /**
     * Renders component
     */
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, { children: [(0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ ref: (ref) => {
                    popperRef.current = ref;
                }, "aria-haspopup": "true", onClick: handleOpen, className: classes.button, size: "small" }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "expand_more" }) })), isMobile ? ((0, jsx_runtime_1.jsx)(material_1.SwipeableDrawer, Object.assign({ open: open, onClose: handleClose, onOpen: handleOpen, anchor: "bottom", disableSwipeToOpen: true }, { children: renderContent() }))) : ((0, jsx_runtime_1.jsx)(PopperRoot, Object.assign({ open: open, anchorEl: popperRef.current, role: undefined, transition: true, className: classes.popperRoot }, PopperProps, { placement: "right" }, { children: ({ TransitionProps, placement }) => ((0, jsx_runtime_1.jsx)(material_1.Grow, Object.assign({}, TransitionProps, { style: { transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom' } }, { children: (0, jsx_runtime_1.jsx)(material_1.Paper, Object.assign({ variant: 'outlined', className: classes.paper }, { children: (0, jsx_runtime_1.jsx)(material_1.ClickAwayListener, Object.assign({ onClickAway: handleClose }, { children: renderContent() })) })) }))) }))), openConfirmDialog && ((0, jsx_runtime_1.jsx)(ConfirmDialog_1.default, Object.assign({ open: openConfirmDialog }, (currentAction === constants_1.BAN_ROOM_USER
                ? {
                    content: ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.liveStreamRoom.participantTileActions.banRoomUser", defaultMessage: "ui.liveStreamRoom.participantTileActions.banRoomUser" }))
                }
                : {}), { onConfirm: handleConfirmedAction, isUpdating: Boolean(currentActionLoading), onClose: () => setOpenConfirmDialog(false) })))] })));
}
exports.default = ContributionActionsMenu;
