"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 system_1 = require("@mui/system");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const types_1 = require("@selfcommunity/types");
const utils_1 = require("@selfcommunity/utils");
const react_1 = require("react");
const react_intl_1 = require("react-intl");
require("swiper/css");
const Errors_1 = require("../../constants/Errors");
const Pagination_1 = require("../../constants/Pagination");
const BaseDialog_1 = tslib_1.__importDefault(require("../../shared/BaseDialog"));
const HiddenPlaceholder_1 = tslib_1.__importDefault(require("../../shared/HiddenPlaceholder"));
const InfiniteScroll_1 = tslib_1.__importDefault(require("../../shared/InfiniteScroll"));
const widget_1 = require("../../utils/widget");
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const constants_1 = require("./constants");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const LiveStream_1 = tslib_1.__importStar(require("../LiveStream"));
const messages = (0, react_intl_1.defineMessages)({
    title: {
        id: 'ui.userLiveStreamWidget.title',
        defaultMessage: 'ui.userLiveStreamWidget.title'
    }
});
const classes = {
    root: `${constants_1.PREFIX}-root`,
    content: `${constants_1.PREFIX}-content`,
    header: `${constants_1.PREFIX}-header`,
    avatarWrapper: `${constants_1.PREFIX}-avatar-wrapper`,
    avatar: `${constants_1.PREFIX}-avatar`,
    liveWrapper: `${constants_1.PREFIX}-live-wrapper`,
    live: `${constants_1.PREFIX}-live`,
    actions: `${constants_1.PREFIX}-actions`,
    actionButton: `${constants_1.PREFIX}-action-button`,
    dialogRoot: `${constants_1.PREFIX}-dialog-root`,
    infiniteScroll: `${constants_1.PREFIX}-infinite-scroll`,
    endMessage: `${constants_1.PREFIX}-end-message`
};
const Root = (0, system_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root
})(() => ({}));
const DialogRoot = (0, system_1.styled)(BaseDialog_1.default, {
    name: constants_1.PREFIX,
    slot: 'DialogRoot',
    overridesResolver: (_props, styles) => styles.dialogRoot
})(() => ({}));
function UserLiveStreamWidget(inProps) {
    // PROPS
    const props = (0, material_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { userId, user, liveStreamComponentProps = { elevation: 0, square: true }, endpointQueryParams = { limit: 5, offset: Pagination_1.DEFAULT_PAGINATION_OFFSET }, cacheStrategy, dialogProps, limit = 5 } = props, rest = tslib_1.__rest(props, ["userId", "user", "liveStreamComponentProps", "endpointQueryParams", "cacheStrategy", "dialogProps", "limit"]);
    // STATE
    const [state, dispatch] = (0, react_1.useReducer)(widget_1.dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: react_core_1.SCCache.getWidgetStateCacheKey(react_core_1.SCCache.USER_LIVE_STREAM_CACHE_PREFIX_KEY, (0, utils_1.isInteger)(userId) ? userId : user.id),
        cacheStrategy,
        visibleItems: limit
    }, widget_1.stateWidgetInitializer);
    const [openDialog, setOpenDialog] = (0, react_1.useState)(false);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    const scPreferencesContext = (0, react_core_1.useSCPreferences)();
    const { scUser } = (0, react_core_1.useSCFetchUser)({ id: userId, user });
    // HOOKS
    const intl = (0, react_intl_1.useIntl)();
    // MEMO
    const liveStreamEnabled = (0, react_1.useMemo)(() => react_core_1.SCPreferences.CONFIGURATIONS_LIVE_STREAM_ENABLED in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[react_core_1.SCPreferences.CONFIGURATIONS_LIVE_STREAM_ENABLED].value, [scPreferencesContext.preferences]);
    const isFreeTrialTier = (0, react_1.useMemo)(() => scPreferencesContext.preferences &&
        react_core_1.SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[react_core_1.SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER].value &&
        scPreferencesContext.preferences[react_core_1.SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER].value === types_1.SCCommunitySubscriptionTier.FREE_TRIAL, [scPreferencesContext.preferences]);
    const _initComponent = (0, react_1.useCallback)(() => {
        if (!state.initialized && !state.isLoadingNext) {
            dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.UserApiClient.getUserLiveStream(scUser.id, endpointQueryParams)
                .then((payload) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
            })
                .catch((error) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [scUser, state.isLoadingNext, state.initialized, dispatch]);
    // EFFECTS
    (0, react_1.useEffect)(() => {
        let _t;
        if (scUserContext.user && scUser && liveStreamEnabled) {
            _t = setTimeout(_initComponent);
            return () => {
                clearTimeout(_t);
            };
        }
    }, [scUserContext.user, scUser, liveStreamEnabled]);
    // HANDLERS
    /**
     * Handles pagination
     */
    const handleNext = (0, react_1.useCallback)(() => {
        dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
        api_services_1.http
            .request({
            url: state.next,
            method: api_services_1.Endpoints.GetLiveStream.method
        })
            .then((res) => {
            dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next, state.isLoadingNext, state.initialized]);
    const handleToggleDialogOpen = (0, react_1.useCallback)(() => {
        setOpenDialog((prev) => !prev);
    }, []);
    if (!scUser && !state.initialized) {
        return (0, jsx_runtime_1.jsx)(Skeleton_1.default, {});
    }
    if (!scUser || (state === null || state === void 0 ? void 0 : state.count) === 0 || !liveStreamEnabled || isFreeTrialTier) {
        return (0, jsx_runtime_1.jsx)(HiddenPlaceholder_1.default, {});
    }
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: classes.root }, rest, { children: [(0, jsx_runtime_1.jsxs)(material_1.CardContent, Object.assign({ className: classes.content }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h4" }, { children: (0, jsx_runtime_1.jsx)("b", { children: intl.formatMessage(messages.title, { user: scUser.username }) }) })), (0, jsx_runtime_1.jsx)(material_1.Stack, Object.assign({ className: classes.liveWrapper }, { children: state === null || state === void 0 ? void 0 : state.results.map((_live, i, array) => ((0, jsx_runtime_1.jsxs)(react_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(LiveStream_1.default, Object.assign({ liveStream: _live }, liveStreamComponentProps, { className: classes.live })), i < array.length - 1 && (0, jsx_runtime_1.jsx)(material_1.Divider, {})] }, i))) }))] })), state.count > state.visibleItems && ((0, jsx_runtime_1.jsx)(material_1.CardActions, Object.assign({ className: classes.actions }, { children: (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ onClick: handleToggleDialogOpen, className: classes.actionButton }, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "caption" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.userLiveStreamWidget.showAll", defaultMessage: "ui.userLiveStreamWidget.showAll" }) })) })) }))), openDialog && ((0, jsx_runtime_1.jsx)(DialogRoot, Object.assign({ className: classes.dialogRoot, title: intl.formatMessage(messages.title, { user: scUser.username }), onClose: handleToggleDialogOpen, open: openDialog }, dialogProps, { children: (0, jsx_runtime_1.jsx)(InfiniteScroll_1.default, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: (0, jsx_runtime_1.jsx)(LiveStream_1.LiveStreamSkeleton, Object.assign({ elevation: 0 }, liveStreamComponentProps)), className: classes.infiniteScroll, endMessage: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.endMessage }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.userLiveStreamWidget.noMoreResults", defaultMessage: "ui.userLiveStreamWidget.noMoreResults" }) })) }, { children: (0, jsx_runtime_1.jsx)(material_1.List, { children: state.results.map((live) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(LiveStream_1.default, Object.assign({ elevation: 0, liveStream: live }, liveStreamComponentProps)) }, live.id))) }) })) })))] })));
}
exports.default = UserLiveStreamWidget;
