"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importStar(require("react"));
const styles_1 = require("@mui/material/styles");
const react_intl_1 = require("react-intl");
const CommentObject_1 = tslib_1.__importStar(require("../CommentObject"));
const Typography_1 = tslib_1.__importDefault(require("@mui/material/Typography"));
const material_1 = require("@mui/material");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const CustomAdv_1 = tslib_1.__importDefault(require("../CustomAdv"));
const system_1 = require("@mui/system");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const react_intersection_observer_1 = require("react-intersection-observer");
const contribution_1 = require("../../utils/contribution");
const types_1 = require("@selfcommunity/types");
const utils_1 = require("@selfcommunity/utils");
const Pagination_1 = require("../../constants/Pagination");
const react_core_1 = require("@selfcommunity/react-core");
const constants_1 = require("./constants");
const classes = {
    root: `${constants_1.PREFIX}-root`,
    loadNextCommentsButton: `${constants_1.PREFIX}-load-more-comments-button`,
    loadPreviousCommentsButton: `${constants_1.PREFIX}-load-previous-comments-button`,
    paginationLink: `${constants_1.PREFIX}-pagination-link`,
    pagination: `${constants_1.PREFIX}-pagination`,
    commentsCounter: `${constants_1.PREFIX}-comments-counter`,
    commentNotFound: `${constants_1.PREFIX}-comment-not-found`,
    noOtherComments: `${constants_1.PREFIX}-no-other-comment`
};
const Root = (0, styles_1.styled)(material_1.Box, {
    name: constants_1.PREFIX,
    slot: 'Root'
})(() => ({}));
const PREFERENCES = [react_core_1.SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED, react_core_1.SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED];
/**
 * > API documentation for the Community-JS Comments Object component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCCommentsObject-root|Styles applied to the root element.|
 |pagination|.SCCommentsObject-pagination|Styles applied to the pagination controls.|
 |paginationLink|.SCCommentsObject-pagination-link|Styles applied to the pagination link.|
 |loadNextCommentsButton|.SCCommentsObject-load-next-comments-button|Styles applied to the load next comments button.|
 |loadPreviousCommentsButton|.SCCommentsObject-load-previous-comments-button|Styles applied to the load previous comments button.|
 |commentsCounter|.SCCommentsObject-comments-counter|Styles applied to the comments counter element.|

 * @param inProps
 */
function CommentsObject(inProps) {
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    // PROPS
    const { id = `comments_object_${props.feedObjectId ? props.feedObjectId : props.feedObject ? props.feedObject.id : ''}`, className, feedObjectId, feedObject, feedObjectType = types_1.SCContributionType.POST, CommentComponent = CommentObject_1.default, CommentComponentProps = { variant: 'outlined' }, CommentObjectSkeletonProps = { elevation: 0, WidgetProps: { variant: 'outlined' } }, CommentsObjectSkeletonProps = {}, next, isLoadingNext, handleNext, previous, isLoadingPrevious, handlePrevious, totalLoadedComments, totalComments, page, previousPage, nextPage, comments = [], startComments = [], endComments = [], infiniteScrolling = false, hideAdvertising = false, disablePaginationLinks = false, hidePaginationLinks = true, inPlaceLoadMoreContents = true, paginationLinksPageQueryParam = Pagination_1.DEFAULT_PAGINATION_QUERY_PARAM_NAME, PaginationLinkProps = {}, cacheStrategy = utils_1.CacheStrategies.NETWORK_ONLY } = props, rest = tslib_1.__rest(props, ["id", "className", "feedObjectId", "feedObject", "feedObjectType", "CommentComponent", "CommentComponentProps", "CommentObjectSkeletonProps", "CommentsObjectSkeletonProps", "next", "isLoadingNext", "handleNext", "previous", "isLoadingPrevious", "handlePrevious", "totalLoadedComments", "totalComments", "page", "previousPage", "nextPage", "comments", "startComments", "endComments", "infiniteScrolling", "hideAdvertising", "disablePaginationLinks", "hidePaginationLinks", "inPlaceLoadMoreContents", "paginationLinksPageQueryParam", "PaginationLinkProps", "cacheStrategy"]);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    const scPreferences = (0, react_core_1.useSCPreferences)();
    const scRoutingContext = (0, react_core_1.useSCRouting)();
    const { obj } = (0, react_core_1.useSCFetchFeedObject)({ id: feedObjectId, feedObject, feedObjectType, cacheStrategy });
    const commentsIds = comments.map((c) => c.id);
    const advPosition = Math.floor(Math.random() * (Math.min(comments.length, 5) - 1 + 1) + 1);
    /**
     * Compute preferences
     */
    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]);
    /**
     * Render advertising above FeedObject Detail
     */
    const renderAdvertising = (0, react_1.useMemo)(() => () => {
        if (obj &&
            !hideAdvertising &&
            preferences[react_core_1.SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED] &&
            ((preferences[react_core_1.SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED] && scUserContext.user === null) ||
                !preferences[react_core_1.SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED])) {
            return ((0, jsx_runtime_1.jsx)(CustomAdv_1.default, Object.assign({ position: types_1.SCCustomAdvPosition.POSITION_IN_COMMENTS }, (obj.categories.length && { categoriesId: obj.categories.map((c) => c.id) }))));
        }
        return null;
    }, [JSON.stringify(obj)]);
    /**
     * Handle open reply box
     * @param comment
     */
    function openReplyBox(comment) {
        setTimeout(() => {
            const element = document.getElementById(`reply-${comment.id}`);
            if (element) {
                element.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
            }
        }, 200);
    }
    /**
     * handle on scroll end
     * @param inView
     * @param entry
     */
    function handleScrollEnd(inView, entry) {
        if (infiniteScrolling && inView && !isLoadingNext) {
            handleNext && handleNext();
        }
    }
    /**
     * Check if show Comments counter
     */
    function showCommentsCounter() {
        return Boolean(totalComments && totalLoadedComments);
    }
    /**
     * Render button load previous comments
     */
    function renderLoadPreviousComments() {
        return ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.pagination }, { children: [isLoadingPrevious && (0, jsx_runtime_1.jsx)(CommentObject_1.CommentObjectSkeleton, Object.assign({}, CommentObjectSkeletonProps, { count: 1 })), !isLoadingPrevious && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ variant: "text" }, (inPlaceLoadMoreContents
                            ? { onClick: handlePrevious }
                            : {
                                component: react_core_1.Link,
                                to: `${scRoutingContext.url((0, contribution_1.getContributionRouteName)(feedObject), (0, contribution_1.getRouteData)(feedObject))}`
                            }), { disabled: isLoadingPrevious, color: "inherit", classes: { root: classes.loadPreviousCommentsButton } }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.commentsObject.loadPreviousComments", defaultMessage: "ui.commentsObject.loadPreviousComments" }) })), !disablePaginationLinks && previousPage && previous && ((0, jsx_runtime_1.jsx)(react_core_1.Link, Object.assign({ to: `${(0, utils_1.appendURLSearchParams)(scRoutingContext.url((0, contribution_1.getContributionRouteName)(feedObject), (0, contribution_1.getRouteData)(feedObject)), [
                                { [paginationLinksPageQueryParam]: previousPage }
                            ])}`, className: (0, classnames_1.default)({ [classes.paginationLink]: hidePaginationLinks }) }, PaginationLinkProps, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.commentsObject.previousComments", defaultMessage: "ui.commentsObject.previousComments" }) })))] }))] })));
    }
    /**
     * Footer with n comments of, only for load more pagination mode
     */
    function renderLoadNextComments() {
        return ((0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ className: classes.pagination }, { children: isLoadingNext ? ((0, jsx_runtime_1.jsx)(CommentObject_1.CommentObjectSkeleton, Object.assign({}, CommentObjectSkeletonProps, { count: 1 }))) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(react_intersection_observer_1.InView, Object.assign({ as: "div", onChange: handleScrollEnd, threshold: 0.5 }, { children: (0, jsx_runtime_1.jsxs)(material_1.Stack, Object.assign({ direction: "row", justifyContent: "space-between", alignItems: "center", spacing: 2 }, { children: [(0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ variant: "text" }, (inPlaceLoadMoreContents
                                    ? { onClick: handleNext }
                                    : {
                                        component: react_core_1.Link,
                                        to: nextPage && next
                                            ? `${(0, utils_1.appendURLSearchParams)(scRoutingContext.url((0, contribution_1.getContributionRouteName)(feedObject), (0, contribution_1.getRouteData)(feedObject)), [
                                                { [paginationLinksPageQueryParam]: nextPage }
                                            ])}`
                                            : `${scRoutingContext.url((0, contribution_1.getContributionRouteName)(feedObject), (0, contribution_1.getRouteData)(feedObject))}`
                                    }), { disabled: isLoadingNext, color: "inherit", classes: { root: classes.loadNextCommentsButton } }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.commentsObject.loadMoreComments", defaultMessage: "ui.commentsObject.loadMoreComments" }) })), showCommentsCounter() && ((0, jsx_runtime_1.jsx)(Typography_1.default, Object.assign({ variant: "body1", classes: { root: classes.commentsCounter } }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.commentsObject.numberOfComments", defaultMessage: "ui.commentsObject.numberOfComments", values: { loaded: totalLoadedComments, total: totalComments } }) })))] })) })), !disablePaginationLinks && nextPage && next && ((0, jsx_runtime_1.jsx)(react_core_1.Link, Object.assign({ to: `${(0, utils_1.appendURLSearchParams)(scRoutingContext.url((0, contribution_1.getContributionRouteName)(feedObject), (0, contribution_1.getRouteData)(feedObject)), [
                            { [paginationLinksPageQueryParam]: nextPage }
                        ])}`, className: (0, classnames_1.default)({ [classes.paginationLink]: hidePaginationLinks }) }, PaginationLinkProps, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.commentsObject.nextComments", defaultMessage: "ui.commentsObject.nextComments" }) })))] })) })));
    }
    /**
     * Remove duplicate comments (from header or footer)
     * @param comments
     */
    function getFilteredComments(comments) {
        return comments.filter((c) => !commentsIds.includes(c.id));
    }
    /**
     * Render comments and load others with load more button
     */
    function renderComments(comments) {
        return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: comments.map((comment, index) => ((0, jsx_runtime_1.jsxs)(react_1.default.Fragment, { children: [(0, jsx_runtime_1.jsx)(CommentComponent, Object.assign({ commentObject: comment, onOpenReply: openReplyBox, feedObject: obj }, CommentComponentProps, { CommentObjectSkeletonProps: CommentObjectSkeletonProps }), comment.id), advPosition === index && renderAdvertising()] }, index))) }));
    }
    /**
     * Render comments
     */
    let commentsRendered = (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {});
    if (!obj || ((isLoadingPrevious || isLoadingNext) && !comments.length)) {
        /**
         * Until the contribution has not been founded and there are
         * no comments during loading render skeletons
         */
        commentsRendered = (0, jsx_runtime_1.jsx)(Skeleton_1.default, Object.assign({ CommentObjectSkeletonProps: CommentObjectSkeletonProps }, CommentsObjectSkeletonProps));
    }
    else {
        /**
         * Two modes available:
         *  - infinite scroll
         *  - load pagination with load next comment button
         *  !IMPORTANT:
         *  the component will switch to 'load more pagination' mode automatically
         *  in case it needs to display a single comment or newComments
         */
        commentsRendered = ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [previous && renderLoadPreviousComments(), renderComments(comments), next && renderLoadNextComments()] }));
    }
    /**
     * Renders root object
     */
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ id: id, className: (0, classnames_1.default)(classes.root, className) }, rest, { children: [renderComments(getFilteredComments(startComments)), commentsRendered, renderComments(getFilteredComments(endComments))] })));
}
exports.default = CommentsObject;
