"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 types_1 = require("@selfcommunity/types");
const react_core_1 = require("@selfcommunity/react-core");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const system_1 = require("@mui/system");
const constants_1 = require("./constants");
const ChangeGroupCover_1 = tslib_1.__importDefault(require("../ChangeGroupCover"));
const react_intl_1 = require("react-intl");
const Bullet_1 = tslib_1.__importDefault(require("../../shared/Bullet"));
const ChangeGroupPicture_1 = tslib_1.__importDefault(require("../ChangeGroupPicture"));
const GroupMembersButton_1 = tslib_1.__importDefault(require("../GroupMembersButton"));
const EditGroupButton_1 = tslib_1.__importDefault(require("../EditGroupButton"));
const GroupSubscribeButton_1 = tslib_1.__importDefault(require("../GroupSubscribeButton"));
const GroupInviteButton_1 = tslib_1.__importDefault(require("../GroupInviteButton"));
const PubSub_1 = require("../../constants/PubSub");
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const GroupActionsMenu_1 = tslib_1.__importDefault(require("../GroupActionsMenu"));
const classes = {
    root: `${constants_1.PREFIX}-root`,
    cover: `${constants_1.PREFIX}-cover`,
    avatar: `${constants_1.PREFIX}-avatar`,
    info: `${constants_1.PREFIX}-info`,
    name: `${constants_1.PREFIX}-name`,
    changePicture: `${constants_1.PREFIX}-change-picture`,
    changeCover: `${constants_1.PREFIX}-change-cover`,
    visibility: `${constants_1.PREFIX}-visibility`,
    visibilityItem: `${constants_1.PREFIX}-visibility-item`,
    members: `${constants_1.PREFIX}-members`,
    membersCounter: `${constants_1.PREFIX}-members-counter`,
    multiActions: `${constants_1.PREFIX}-multi-actions`
};
const Root = (0, styles_1.styled)(material_1.Box, {
    name: constants_1.PREFIX,
    slot: 'Root'
})(() => ({}));
/**
 * > API documentation for the Community-JS Group Header component. Learn about the available props and the CSS API.
 *
 *
 * This component renders the groups top section.

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCGroupHeader-root|Styles applied to the root element.|
 |cover|.SCGroupHeader-cover|Styles applied to the cover element.|
 |avatar|.SCGroupHeader-avatar|Styles applied to the avatar element.|
 |info|SCGroupHeader-info|Styles applied to the info section.|
 |name|SCGroupHeader-username|Styles applied to the username element.|
 |changePicture|.SCGroupHeader-change-picture|Styles applied to changePicture element.|
 |changeCover|.SCGroupHeader-change-cover`|Styles applied to changeCover element.|

 * @param inProps
 */
function GroupHeader(inProps) {
    var _a;
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { id = null, className = null, group, groupId = null, ChangePictureProps = {}, ChangeCoverProps = {}, GroupSubscribeButtonProps = {}, GroupMembersButtonProps = {}, GroupActionsProps } = props, rest = tslib_1.__rest(props, ["id", "className", "group", "groupId", "ChangePictureProps", "ChangeCoverProps", "GroupSubscribeButtonProps", "GroupMembersButtonProps", "GroupActionsProps"]);
    // PREFERENCES
    const scPreferences = (0, react_core_1.useSCPreferences)();
    const visibilityEnabled = (0, react_1.useMemo)(() => scPreferences.preferences[react_core_1.SCPreferences.CONFIGURATIONS_GROUPS_VISIBILITY_ENABLED].value, [scPreferences.preferences]);
    const privateEnabled = (0, react_1.useMemo)(() => scPreferences.preferences[react_core_1.SCPreferences.CONFIGURATIONS_GROUPS_PRIVATE_ENABLED].value, [scPreferences.preferences]);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    // HOOKS
    const { scGroup, setSCGroup } = (0, react_core_1.useSCFetchGroup)({ id: groupId, group });
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    // REFS
    const updatesSubscription = (0, react_1.useRef)(null);
    // CONST
    const isGroupAdmin = (0, react_1.useMemo)(() => { var _a; return scUserContext.user && ((_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id) === scUserContext.user.id; }, [scUserContext.user, (_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id]);
    /**
     * Handles Change Avatar
     * @param avatar
     */
    function handleChangeAvatar(avatar) {
        if (isGroupAdmin) {
            setSCGroup(Object.assign({}, scGroup, { image_big: avatar }));
        }
    }
    /**
     * Handles Change Cover
     * @param cover
     */
    function handleChangeCover(cover) {
        if (isGroupAdmin) {
            setSCGroup(Object.assign({}, scGroup, { emotional_image: cover }));
        }
    }
    /**
     * Handles callback subscribe/unsubscribe group
     */
    const handleSubscribe = (group, status) => {
        setSCGroup(Object.assign(Object.assign({}, group), { subscribers_counter: group.subscribers_counter + (status ? 1 : -1) }));
    };
    /**
     * Subscriber for pubsub callback
     */
    const onChangeGroupMembersHandler = (0, react_1.useCallback)((msg, data) => {
        var _a;
        if (data && ((_a = data === null || data === void 0 ? void 0 : data.group) === null || _a === void 0 ? void 0 : _a.id) === (scGroup === null || scGroup === void 0 ? void 0 : scGroup.id)) {
            let _group = Object.assign({}, scGroup);
            if (msg === `${PubSub_1.SCTopicType.GROUP}.${PubSub_1.SCGroupEventType.ADD_MEMBER}`) {
                _group.subscribers_counter = _group.subscribers_counter + 1;
            }
            else if (msg === `${PubSub_1.SCTopicType.GROUP}.${PubSub_1.SCGroupEventType.REMOVE_MEMBER}`) {
                _group.subscribers_counter = Math.max(_group.subscribers_counter - 1, 0);
            }
            setSCGroup(_group);
        }
    }, [scGroup, setSCGroup]);
    /**
     * On mount, subscribe to receive groups updates (only edit)
     */
    (0, react_1.useEffect)(() => {
        if (scGroup) {
            updatesSubscription.current = pubsub_js_1.default.subscribe(`${PubSub_1.SCTopicType.GROUP}.${PubSub_1.SCGroupEventType.MEMBERS}`, onChangeGroupMembersHandler);
        }
        return () => {
            updatesSubscription.current && pubsub_js_1.default.unsubscribe(updatesSubscription.current);
        };
    }, [scGroup]);
    // RENDER
    if (!scGroup) {
        return (0, jsx_runtime_1.jsx)(Skeleton_1.default, {});
    }
    const _backgroundCover = Object.assign({}, (scGroup.emotional_image
        ? { background: `url('${scGroup.emotional_image}') center / cover` }
        : { background: `url('${scPreferences.preferences[react_core_1.SCPreferences.IMAGES_USER_DEFAULT_COVER].value}') center / cover` }));
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ id: id, className: (0, classnames_1.default)(classes.root, className) }, rest, { children: [(0, jsx_runtime_1.jsxs)(material_1.Paper, Object.assign({ style: _backgroundCover, classes: { root: classes.cover } }, { children: [(0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ className: classes.avatar }, { children: (0, jsx_runtime_1.jsx)(material_1.Avatar, { children: (0, jsx_runtime_1.jsx)("img", { alt: "group", src: scGroup.image_big ? scGroup.image_big : '' }) }) })), isGroupAdmin && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(ChangeGroupPicture_1.default, Object.assign({ groupId: scGroup.id, onChange: handleChangeAvatar, className: classes.changePicture }, ChangePictureProps)), (0, jsx_runtime_1.jsx)("div", Object.assign({ className: classes.changeCover }, { children: (0, jsx_runtime_1.jsx)(ChangeGroupCover_1.default, Object.assign({ groupId: scGroup.id, onChange: handleChangeCover }, ChangeCoverProps)) }))] }))] })), (0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.info }, { children: [isGroupAdmin && !isMobile && ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.multiActions }, { children: [(0, jsx_runtime_1.jsx)(EditGroupButton_1.default, { group: scGroup, groupId: scGroup.id, onEditSuccess: (data) => setSCGroup(data) }), (0, jsx_runtime_1.jsx)(GroupActionsMenu_1.default, Object.assign({ group: scGroup, onEditSuccess: (data) => setSCGroup(data) }, GroupActionsProps))] }))), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h5", className: classes.name }, { children: scGroup.name })), privateEnabled && ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.visibility }, { children: [privateEnabled && ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: scGroup.privacy === types_1.SCGroupPrivacyType.PUBLIC ? ((0, jsx_runtime_1.jsxs)(material_1.Typography, Object.assign({ className: classes.visibilityItem }, { children: [(0, jsx_runtime_1.jsx)(material_1.Icon, { children: "public" }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupHeader.visibility.public", defaultMessage: "ui.groupHeader.visibility.public" })] }))) : ((0, jsx_runtime_1.jsxs)(material_1.Typography, Object.assign({ className: classes.visibilityItem }, { children: [(0, jsx_runtime_1.jsx)(material_1.Icon, { children: "private" }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupHeader.visibility.private", defaultMessage: "ui.groupHeader.visibility.private" })] }))) })), visibilityEnabled && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [privateEnabled && (0, jsx_runtime_1.jsx)(Bullet_1.default, {}), scGroup.visible ? ((0, jsx_runtime_1.jsxs)(material_1.Typography, Object.assign({ className: classes.visibilityItem }, { children: [(0, jsx_runtime_1.jsx)(material_1.Icon, { children: "visibility" }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupHeader.visibility.visible", defaultMessage: "ui.groupHeader.visibility.visible" })] }))) : ((0, jsx_runtime_1.jsxs)(material_1.Typography, Object.assign({ className: classes.visibilityItem }, { children: [(0, jsx_runtime_1.jsx)(material_1.Icon, { children: "visibility_off" }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupHeader.visibility.hidden", defaultMessage: "ui.groupHeader.visibility.hidden" })] })))] }))] }))), (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: ((scGroup && scGroup.privacy === types_1.SCGroupPrivacyType.PUBLIC) ||
                            scGroup.subscription_status === types_1.SCGroupSubscriptionStatusType.SUBSCRIBED ||
                            isGroupAdmin) && ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.members }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.membersCounter, component: "div" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupHeader.members", defaultMessage: "ui.groupHeader.members", values: { total: scGroup.subscribers_counter } }) })), (0, jsx_runtime_1.jsx)(GroupMembersButton_1.default, Object.assign({ groupId: scGroup === null || scGroup === void 0 ? void 0 : scGroup.id, group: scGroup, autoHide: !isGroupAdmin }, GroupMembersButtonProps), scGroup.subscribers_counter)] }))) }), isGroupAdmin ? ((0, jsx_runtime_1.jsxs)(material_1.Box, { children: [(0, jsx_runtime_1.jsx)(GroupInviteButton_1.default, { group: scGroup, groupId: scGroup.id }), isMobile && (0, jsx_runtime_1.jsx)(GroupActionsMenu_1.default, Object.assign({ group: scGroup, onEditSuccess: (data) => setSCGroup(data) }, GroupActionsProps))] })) : ((0, jsx_runtime_1.jsx)(GroupSubscribeButton_1.default, Object.assign({ group: scGroup, onSubscribe: handleSubscribe }, GroupSubscribeButtonProps)))] }))] })));
}
exports.default = GroupHeader;
