"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 material_1 = require("@mui/material");
const styles_1 = require("@mui/material/styles");
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const react_intl_1 = require("react-intl");
const Errors_1 = require("../../constants/Errors");
const MarkRead_1 = tslib_1.__importDefault(require("../../shared/MarkRead"));
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const types_1 = require("../../types");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const api_services_1 = require("@selfcommunity/api-services");
const utils_1 = require("@selfcommunity/utils");
const react_core_1 = require("@selfcommunity/react-core");
const constants_1 = require("./constants");
const classes = {
    root: `${constants_1.PREFIX}-message-root`,
    header: `${constants_1.PREFIX}-header`,
    title: `${constants_1.PREFIX}-title`,
    media: `${constants_1.PREFIX}-media`,
    content: `${constants_1.PREFIX}-content`,
    listItemSnippet: `${constants_1.PREFIX}-list-item-snippet`,
    listItemSnippetNew: `${constants_1.PREFIX}-list-item-snippet-new`,
    messageIconWrap: `${constants_1.PREFIX}-flag-icon-wrap`,
    messageIconSnippet: `${constants_1.PREFIX}-flag-icon-snippet`
};
const Root = (0, styles_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'MessageRoot'
})(() => ({}));
const PREFERENCES = [react_core_1.SCPreferences.LOGO_NAVBAR_LOGO_MOBILE, react_core_1.SCPreferences.TEXT_APPLICATION_NAME];
function Message(props) {
    // PROPS
    const { id = `message_${props.message.id}`, className, message, disableMarkRead = false, onClose = null, onRead = null, template = types_1.SCBroadcastMessageTemplateType.DETAIL } = props, rest = tslib_1.__rest(props, ["id", "className", "message", "disableMarkRead", "onClose", "onRead", "template"]);
    // STATE
    const [open, setOpen] = (0, react_1.useState)(message.disposed_at === null);
    const [closing, setClosing] = (0, react_1.useState)(false);
    // CONTEXT
    const scPrefernces = (0, react_1.useContext)(react_core_1.SCPreferencesContext);
    // ROUTING
    const scRoutingContext = (0, react_core_1.useSCRouting)();
    // Compute preferences
    const preferences = (0, react_1.useMemo)(() => {
        const _preferences = {};
        PREFERENCES.map((p) => (_preferences[p] = p in scPrefernces.preferences ? scPrefernces.preferences[p].value : null));
        return _preferences;
    }, [scPrefernces.preferences]);
    // HANDLERS
    /**
     * Handle dispose message
     */
    const handleClose = () => {
        setClosing(true);
        api_services_1.http
            .request({
            url: api_services_1.Endpoints.BroadcastMessagesDispose.url(),
            method: api_services_1.Endpoints.BroadcastMessagesDispose.method,
            data: {
                banner_ids: [message.id]
            }
        })
            .then(() => {
            setOpen(false);
            setClosing(false);
            onClose && onClose(message);
        })
            .catch((error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
        });
    };
    /**
     * Handle on read message
     * @param res
     */
    const handleOnRead = (res) => {
        if (res.status < 300) {
            onRead && onRead(message);
        }
    };
    (0, react_1.useEffect)(() => {
        setOpen(message.disposed_at === null);
    }, [message]);
    // RENDER
    const renderContent = (banner) => {
        return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.CardContent, Object.assign({ className: classes.title }, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h6" }, { children: banner.title })) })), banner.image && (0, jsx_runtime_1.jsx)(material_1.CardMedia, { className: classes.media, component: "img", image: banner.image, alt: banner.title }), (banner.body_text || banner.link_text) && ((0, jsx_runtime_1.jsxs)(material_1.CardContent, Object.assign({ className: classes.content }, { children: [banner.body_text && ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "body1", color: "text.secondary" }, { children: banner.body_text }))), banner.link_text && ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "body1", color: "text.secondary" }, { children: (0, jsx_runtime_1.jsx)("a", Object.assign({ href: banner.link, target: banner.open_in_new_tab ? '_blank' : '_self' }, { children: banner.link_text })) })))] })))] }));
    };
    // Banner
    const { banner } = message;
    if (template === types_1.SCBroadcastMessageTemplateType.DETAIL || types_1.SCBroadcastMessageTemplateType.TOAST) {
        /**
         * With a fade in transition show the Card (Widget)
         * Include also MarkRead component to
         */
        return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ id: id, className: (0, classnames_1.default)(classes.root, className) }, rest, { children: (0, jsx_runtime_1.jsx)(material_1.Fade, Object.assign({ in: open, unmountOnExit: true }, { children: (0, jsx_runtime_1.jsxs)(material_1.Box, { children: [message.viewed_at === null && !disableMarkRead && ((0, jsx_runtime_1.jsx)(MarkRead_1.default, { endpoint: api_services_1.Endpoints.BroadcastMessagesMarkRead, data: { banner_ids: [message.id] }, callback: handleOnRead })), (0, jsx_runtime_1.jsx)(material_1.CardHeader, { className: classes.header, avatar: (0, jsx_runtime_1.jsx)(material_1.Avatar, { alt: preferences[react_core_1.SCPreferences.TEXT_APPLICATION_NAME], src: preferences[react_core_1.SCPreferences.LOGO_NAVBAR_LOGO_MOBILE] }), action: template === types_1.SCBroadcastMessageTemplateType.DETAIL && ((0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ "aria-label": "close", onClick: handleClose, disabled: closing }, { children: closing ? (0, jsx_runtime_1.jsx)(material_1.CircularProgress, { size: 20 }) : (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "close" }) }))), title: (0, jsx_runtime_1.jsx)(material_1.Chip, { color: "secondary", size: "small", label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.broadcastMessages.message.chip", defaultMessage: "ui.broadcastMessages.message.chip" }) }) }), renderContent(banner)] }) })) })));
    }
    // SCBroadcastMessageTemplateType.SNIPPET
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ id: id, className: className }, rest, { children: (0, jsx_runtime_1.jsxs)(material_1.ListItem, Object.assign({ alignItems: 'center', component: 'div', classes: {
                root: (0, classnames_1.default)(classes.listItemSnippet, classes.listItemSnippetNew)
            } }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemAvatar, Object.assign({ classes: { root: classes.messageIconWrap } }, { children: (0, jsx_runtime_1.jsx)(material_1.Avatar, Object.assign({ variant: "circular", classes: { root: classes.messageIconSnippet } }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "info" }) })) })), (0, jsx_runtime_1.jsx)(material_1.ListItemText, { disableTypography: true, primary: (0, jsx_runtime_1.jsx)(react_core_1.Link, Object.assign({ to: scRoutingContext.url(react_core_1.SCRoutes.USER_NOTIFICATIONS_ROUTE_NAME, {}) }, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ component: "span", color: "inherit" }, { children: banner.title })) })) })] })) })));
}
exports.default = Message;
