"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const material_1 = require("@mui/material");
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const styles_1 = require("@mui/material/styles");
const system_1 = require("@mui/system");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const utils_1 = require("@selfcommunity/utils");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const notistack_1 = require("notistack");
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const react_1 = require("react");
const react_intl_1 = require("react-intl");
const EventForm_1 = tslib_1.__importDefault(require("../../components/EventForm"));
const EventActionsMenu_1 = require("../../constants/EventActionsMenu");
const PubSub_1 = require("../../constants/PubSub");
const ConfirmDialog_1 = tslib_1.__importDefault(require("../../shared/ConfirmDialog/ConfirmDialog"));
const events_1 = require("../../utils/events");
const PREFIX = 'SCEventActionsMenu';
const classes = {
    root: `${PREFIX}-root`,
    drawerRoot: `${PREFIX}-drawer-root`,
    menuRoot: `${PREFIX}-menu-root`,
    paper: `${PREFIX}-paper`,
    item: `${PREFIX}-item`
};
const Root = (0, styles_1.styled)(material_1.IconButton, {
    name: PREFIX,
    slot: 'Root'
})(() => ({}));
const SwipeableDrawerRoot = (0, styles_1.styled)(material_1.SwipeableDrawer, {
    name: PREFIX,
    slot: 'DrawerRoot'
})(() => ({}));
const MenuRoot = (0, styles_1.styled)(material_1.Menu, {
    name: PREFIX,
    slot: 'MenuRoot'
})(() => ({}));
/**
 * > API documentation for the Community-JS EventActionsMenu component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCEventActionsMenu-root|Styles applied to the root element.|
 |drawerRoot|.SCEventActionsMenu-drawer-root|Styles applied to the drawer root element.|
 |menuRoot|.SCEventActionsMenu-menu-root|Styles applied to the menu root element.|
 |paper|.SCEventActionsMenu-paper|Styles applied to the paper element.|
 |item|.SCEventActionsMenu-item|Styles applied to the item element.|


 * @param inProps
 */
function EventActionsMenu(inProps) {
    var _a;
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className, event, eventId, onDeleteConfirm, onEditSuccess } = props, rest = tslib_1.__rest(props, ["className", "event", "eventId", "onDeleteConfirm", "onEditSuccess"]);
    // STATE
    const [anchorEl, setAnchorEl] = (0, react_1.useState)(null);
    const [openConfirmDialog, setOpenConfirmDialog] = (0, react_1.useState)(false);
    const [openEdit, setOpenEdit] = (0, react_1.useState)(false);
    // HOOKS
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    const scRoutingContext = (0, react_core_1.useSCRouting)();
    const scUserContext = (0, react_core_1.useSCUser)();
    const { scEvent, setSCEvent } = (0, react_core_1.useSCFetchEvent)({ id: eventId, event });
    const isEventAdmin = (0, react_1.useMemo)(() => { var _a; return scUserContext.user && ((_a = scEvent === null || scEvent === void 0 ? void 0 : scEvent.managed_by) === null || _a === void 0 ? void 0 : _a.id) === scUserContext.user.id; }, [scUserContext.user, (_a = scEvent === null || scEvent === void 0 ? void 0 : scEvent.managed_by) === null || _a === void 0 ? void 0 : _a.id]);
    const isEventFinished = (0, react_1.useMemo)(() => (0, events_1.checkEventFinished)(scEvent), [scEvent]);
    // HANDLERS
    const handleOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
        setAnchorEl(null);
    };
    const handleEditClick = () => {
        setOpenEdit((o) => !o);
    };
    const handleCloseDialog = () => {
        setOpenConfirmDialog(false);
        setAnchorEl(null);
    };
    const handleEditSuccess = (data) => {
        setSCEvent(data);
        onEditSuccess && onEditSuccess(data);
    };
    /**
     * Handles thread deletion
     */
    function handleDeleteThread() {
        api_services_1.EventService.deleteEvent(scEvent.id)
            .then(() => {
            onDeleteConfirm();
            handleCloseDialog();
            pubsub_js_1.default.publish(`${PubSub_1.SCTopicType.EVENT}.${PubSub_1.SCGroupEventType.DELETE}`, scEvent.id);
        })
            .catch((error) => {
            setOpenConfirmDialog(false);
            console.log(error);
        });
    }
    const createGoogleCalendarLink = (event) => {
        const baseUrl = 'https://www.google.com/calendar/render?action=TEMPLATE';
        return `${baseUrl}&text=${encodeURIComponent(event.name)}&details=${encodeURIComponent(event.description)}&location=${encodeURIComponent(event.geolocation)}&dates=${event.start_date}/${event.end_date}`;
    };
    /**
     * Handles actions
     */
    function handleAction(action) {
        if (action === EventActionsMenu_1.GET_EVENT_LINK) {
            (0, utils_1.copyTextToClipboard)(`${location.protocol}//${location.host}${scRoutingContext.url(react_core_1.SCRoutes.EVENT_ROUTE_NAME, scEvent)}`).then(() => {
                (0, notistack_1.enqueueSnackbar)((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.common.permanentLinkCopied", defaultMessage: "ui.common.permanentLinkCopied" }), {
                    variant: 'success',
                    autoHideDuration: 3000
                });
            });
            handleClose();
        }
        else if (action === EventActionsMenu_1.ADD_EVENT_TO_CALENDAR) {
            window.open(createGoogleCalendarLink(scEvent), '_blank', 'noopener,noreferrer');
            handleClose();
        }
        else if (action === EventActionsMenu_1.CANCEL_EVENT) {
            setOpenConfirmDialog(true);
            handleClose();
        }
    }
    /**
     *
     */
    const renderList = () => {
        return [
            (0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(EventActionsMenu_1.GET_EVENT_LINK) }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemIcon, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "link" }) }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.shared.eventActionsMenu.item.link", defaultMessage: "ui.shared.eventActionsMenu.item.link" })] }), "link"),
            !isEventFinished && ((0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(EventActionsMenu_1.ADD_EVENT_TO_CALENDAR) }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemIcon, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "CalendarIcon" }) }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.shared.eventActionsMenu.item.calendar", defaultMessage: "ui.shared.eventActionsMenu.item.calendar" })] }), "calendar")),
            isEventAdmin &&
                !isEventFinished && [
                (0, jsx_runtime_1.jsx)(material_1.Divider, {}, "divider"),
                isMobile && ((0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ className: classes.item, onClick: handleEditClick }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemIcon, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "edit" }) }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.shared.eventActionsMenu.item.edit", defaultMessage: "ui.shared.eventActionsMenu.item.edit" })] }), "edit")),
                (0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(EventActionsMenu_1.CANCEL_EVENT) }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemIcon, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "close" }) }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.shared.eventActionsMenu.item.cancel", defaultMessage: "ui.shared.eventActionsMenu.item.cancel" })] }), "cancel")
            ]
        ];
    };
    if (!scEvent) {
        return null;
    }
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, rest, { onClick: handleOpen }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "more_vert" }) })), isMobile ? ((0, jsx_runtime_1.jsx)(SwipeableDrawerRoot, Object.assign({ className: classes.drawerRoot, anchor: "bottom", open: Boolean(anchorEl), onClose: handleClose, onOpen: handleOpen, PaperProps: { className: classes.paper }, disableSwipeToOpen: true }, { children: (0, jsx_runtime_1.jsx)(material_1.List, { children: renderList() }) }))) : ((0, jsx_runtime_1.jsx)(MenuRoot, Object.assign({ className: classes.menuRoot, anchorEl: anchorEl, open: Boolean(anchorEl), onClose: handleClose, PaperProps: { className: classes.paper } }, { children: renderList() }))), openConfirmDialog && ((0, jsx_runtime_1.jsx)(ConfirmDialog_1.default, { open: openConfirmDialog, title: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.shared.eventActionsMenu.dialog.msg", defaultMessage: "ui.shared.eventActionsMenu.dialog.msg" }), btnConfirm: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.shared.eventActionsMenu.dialog.confirm", defaultMessage: "ui.shared.eventActionsMenu.dialog.confirm" }), onConfirm: handleDeleteThread, onClose: handleCloseDialog })), openEdit && (0, jsx_runtime_1.jsx)(EventForm_1.default, { onClose: handleEditClick, event: scEvent, onSuccess: handleEditSuccess })] }));
}
exports.default = EventActionsMenu;
