"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 material_1 = require("@mui/material");
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const system_1 = require("@mui/system");
const types_1 = require("@selfcommunity/types");
const utils_1 = require("@selfcommunity/utils");
const react_core_1 = require("@selfcommunity/react-core");
const Message_1 = tslib_1.__importDefault(require("./Message"));
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const react_intl_1 = require("react-intl");
const Skeleton_1 = require("./Skeleton");
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const constants_1 = require("./constants");
const classes = {
    root: `${constants_1.PREFIX}-root`,
    boxLoadMore: `${constants_1.PREFIX}-box-load-more`,
    avatarLoadMore: `${constants_1.PREFIX}-avatar-load-more`,
    buttonLoadMore: `${constants_1.PREFIX}-button-load-more`
};
const Root = (0, styles_1.styled)(material_1.Box, {
    name: constants_1.PREFIX,
    slot: 'Root'
})(() => ({}));
const PREFERENCES = [react_core_1.SCPreferences.LOGO_NAVBAR_LOGO_MOBILE, react_core_1.SCPreferences.TEXT_APPLICATION_NAME];
/**
 * > API documentation for the Community-JS Broadcast Messages component. Learn about the available props and the CSS API.
 *
 *
 * This component handles message broadcasts. It initially displays unseen messages. If all messages have been viewed it will show at most one message.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/BroadcastMessages)

 #### Import
 ```jsx
 import {BroadcastMessages} from '@selfcommunity/react-ui';
 ```
 #### Component Name
 The name `SCBroadcastMessages` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCBroadcastMessages-root|Styles applied to the root element.|
 |boxLoadMore|.SCBroadcastMessages-box-load-more|Styles applied to load more box.|
 |avatarLoadMore|.SCBroadcastMessages-avatar-load-more|Styles applied to load more avatar.|
 |buttonLoadMore|.SCBroadcastMessages-button-load-more|Styles applied to load more button.|

 * @param inProps
 */
function BroadcastMessages(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { id = 'broadcast_messages', className = null, MessageProps = {}, subscriptionChannel = `${types_1.SCNotificationTopicType.INTERACTION}.${types_1.SCNotificationTypologyType.NOTIFICATION_BANNER}`, disableLoader = false, viewAllMessages = false, cacheStrategy = utils_1.CacheStrategies.NETWORK_ONLY, onStateChange, onHeightChange } = props, rest = tslib_1.__rest(props, ["id", "className", "MessageProps", "subscriptionChannel", "disableLoader", "viewAllMessages", "cacheStrategy", "onStateChange", "onHeightChange"]);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    // Compute preferences
    const scPreferences = (0, react_core_1.useSCPreferences)();
    const preferences = (0, react_1.useMemo)(() => {
        const _preferences = {};
        PREFERENCES.map((p) => (_preferences[p] = p in scPreferences.preferences ? scPreferences.preferences[p].value : null));
        return _preferences;
    }, [scPreferences.preferences]);
    // REFS
    const refreshSubscription = (0, react_1.useRef)(null);
    // STATE
    const [viewAll, setViewAll] = (0, react_1.useState)(viewAllMessages);
    const { data, loading, fetchMessages, setMessages } = (0, react_core_1.useSCFetchBroadcastMessages)({ cacheStrategy });
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    const unViewedMessages = data.results.filter((m) => !m.viewed_at);
    const viewedMessageCounter = data.count - unViewedMessages.length + 1;
    /**
     * Dispose a broadcast message
     * @param message
     */
    const handleDisposeMessage = (message) => {
        const _data = setMessages(data.results.filter((m) => m.id != message.id));
        if (_data.results.length <= 1) {
            fetchMessages(true);
        }
    };
    /**
     * Handle mark read message
     * @param message
     */
    const handleMarkRead = (message) => {
        const _data = [...data.results];
        data.results.map((m, i) => {
            if (m.id === message.id) {
                _data[i] = Object.assign(Object.assign({}, m), { viewed_at: new Date() });
            }
        });
        scUserContext.setUnseenNotificationBannersCounter(scUserContext.user.unseen_notification_banners_counter - 1);
        setMessages(_data);
    };
    /**
     * if messages.length < unViewedMessages.length show other message
     * if the difference between the 2 arrays is small fetch remote messages
     */
    const fetchOtherMessages = (0, react_1.useMemo)(() => () => {
        setViewAll(true);
        if ((data.next && viewAll) || (data.next && !viewAll && viewedMessageCounter <= 2)) {
            fetchMessages();
        }
    }, [setViewAll, viewAll, viewedMessageCounter, data.next, fetchMessages]);
    /**
     * On mount, fetch first page of notifications
     */
    (0, react_1.useEffect)(() => {
        let _t;
        if (authUserId !== null && cacheStrategy !== utils_1.CacheStrategies.CACHE_FIRST) {
            // eslint-disable-next-line @typescript-eslint/no-misused-promises
            _t = setTimeout(fetchMessages);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [authUserId]);
    /**
     * Notification subscriber
     */
    const subscriber = (msg, data) => {
        fetchMessages(true);
        setViewAll(false);
    };
    /**
     * When a ws notification arrives, update data
     */
    (0, react_1.useEffect)(() => {
        refreshSubscription.current = pubsub_js_1.default.subscribe(subscriptionChannel, subscriber);
        return () => {
            pubsub_js_1.default.unsubscribe(refreshSubscription.current);
        };
    }, []);
    /**
     * Feed virtual update
     */
    (0, react_1.useEffect)(() => {
        onStateChange && onStateChange({ viewAllMessages: viewAll, cacheStrategy: utils_1.CacheStrategies.CACHE_FIRST, disableLoader: true });
        onHeightChange && onHeightChange();
    }, [data.results.length, loading, viewAll, cacheStrategy]);
    const messagesToShow = [...unViewedMessages, ...data.results.slice(unViewedMessages.length, viewAll ? viewedMessageCounter : 1)];
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ id: id, className: (0, classnames_1.default)(classes.root, className) }, rest, { children: [messagesToShow.map((message, index) => ((0, jsx_runtime_1.jsx)(material_1.Box, { children: (0, jsx_runtime_1.jsx)(Message_1.default, Object.assign({ message: message }, MessageProps, { onClose: handleDisposeMessage, onRead: handleMarkRead })) }, index))), loading && !disableLoader && (0, jsx_runtime_1.jsx)(Skeleton_1.MessageSkeleton, {}), loading !== null && !loading && (data.next || (data.count > 1 && viewedMessageCounter > 0 && !viewAll)) && ((0, jsx_runtime_1.jsx)(Widget_1.default, Object.assign({ className: classes.boxLoadMore }, { children: (0, jsx_runtime_1.jsx)(material_1.CardContent, { children: (0, jsx_runtime_1.jsxs)(material_1.Button, Object.assign({ variant: "text", onClick: fetchOtherMessages, disabled: loading, color: "inherit", classes: { root: classes.buttonLoadMore } }, { children: [(0, jsx_runtime_1.jsx)(material_1.Avatar, { component: "span", className: classes.avatarLoadMore, alt: preferences[react_core_1.SCPreferences.TEXT_APPLICATION_NAME], src: preferences[react_core_1.SCPreferences.LOGO_NAVBAR_LOGO_MOBILE] }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.broadcastMessages.loadMore", defaultMessage: "ui.broadcastMessages.loadMore" })] })) }) })))] })));
}
exports.default = BroadcastMessages;
