"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 styles_1 = require("@mui/material/styles");
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");
const Errors_1 = require("../../constants/Errors");
const Pagination_1 = require("../../constants/Pagination");
const HiddenPlaceholder_1 = tslib_1.__importDefault(require("../../shared/HiddenPlaceholder"));
const event_1 = require("../../types/event");
const widget_1 = require("../../utils/widget");
const Event_1 = tslib_1.__importDefault(require("../Event"));
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const constants_1 = require("./constants");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const PubSub_1 = require("../../constants/PubSub");
const classes = {
    root: `${constants_1.PREFIX}-root`,
    titleWrapper: `${constants_1.PREFIX}-title-wrapper`,
    imageWrapper: `${constants_1.PREFIX}-image-wrapper`,
    image: `${constants_1.PREFIX}-image`,
    content: `${constants_1.PREFIX}-content`,
    nameWrapper: `${constants_1.PREFIX}-name-wrapper`,
    name: `${constants_1.PREFIX}-name`,
    user: `${constants_1.PREFIX}-user`,
    firstDivider: `${constants_1.PREFIX}-first-divider`,
    secondDivider: `${constants_1.PREFIX}-second-divider`,
    actions: `${constants_1.PREFIX}-actions`,
    actionButton: `${constants_1.PREFIX}-action-button`,
    arrows: `${constants_1.PREFIX}-arrows`
};
const Root = (0, styles_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root
})(() => ({}));
function MyEventsWidget(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    // CONST
    const { endpointQueryParams = {
        limit: Pagination_1.DEFAULT_PAGINATION_LIMIT,
        offset: Pagination_1.DEFAULT_PAGINATION_OFFSET,
        subscription_status: types_1.SCEventSubscriptionStatusType.GOING
    }, cacheStrategy } = props, rest = tslib_1.__rest(props, ["endpointQueryParams", "cacheStrategy"]);
    // 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_EVENTS_STATE_CACHE_PREFIX_KEY),
        cacheStrategy,
        visibleItems: 1
    }, widget_1.stateWidgetInitializer);
    const [eventIndex, setEventIndex] = (0, react_1.useState)(0);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    const scRoutingContext = (0, react_core_1.useSCRouting)();
    const { preferences, features } = (0, react_core_1.useSCPreferences)();
    const eventsEnabled = (0, react_1.useMemo)(() => preferences &&
        features &&
        features.includes(types_1.SCFeatureName.TAGGING) &&
        react_core_1.SCPreferences.CONFIGURATIONS_EVENTS_ENABLED in preferences &&
        preferences[react_core_1.SCPreferences.CONFIGURATIONS_EVENTS_ENABLED].value, [preferences, features]);
    // REFS
    const updatesSubscription = (0, react_1.useRef)(null);
    /**
     * Initialize component
     * Fetch data only if the component is not initialized and it is not loading data
     */
    const _initComponent = (0, react_1.useCallback)(() => {
        if (!state.initialized && !state.isLoadingNext) {
            dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.EventService.getUserEvents(Object.assign({}, 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);
            });
        }
    }, [state.isLoadingNext, state.initialized, dispatch]);
    const _fetchNext = (0, react_1.useCallback)(() => {
        dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
        api_services_1.http
            .request({
            url: state.next,
            method: api_services_1.Endpoints.GetUserEvents.method
        })
            .then((res) => {
            dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
            setEventIndex((index) => index + 1);
        })
            .catch((error) => {
            dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
        });
    }, [dispatch, state.next]);
    // EFFECTS
    (0, react_1.useEffect)(() => {
        let _t;
        if (eventsEnabled && scUserContext.user) {
            _t = setTimeout(_initComponent);
            return () => {
                clearTimeout(_t);
            };
        }
    }, [scUserContext.user, eventsEnabled]);
    const handlePrev = (0, react_1.useCallback)(() => {
        setEventIndex(eventIndex - 1);
    }, [eventIndex]);
    const handleNext = (0, react_1.useCallback)(() => {
        if (eventIndex < state.results.length - 1) {
            setEventIndex(eventIndex + 1);
        }
        else {
            _fetchNext();
        }
    }, [eventIndex, state.results]);
    /**
     * Subscriber for pubsub callback
     */
    const onDeleteEventHandler = (0, react_1.useCallback)((_msg, deleted) => {
        const _events = [...state.results];
        if (_events.some((e) => e.id === deleted)) {
            const updatedEvents = _events.filter((e) => e.id !== deleted);
            dispatch({
                type: widget_1.actionWidgetTypes.SET_RESULTS,
                payload: { results: updatedEvents }
            });
        }
    }, [state.results]);
    /**
     * On mount, subscribe to receive event updates (only delete)
     */
    (0, react_1.useEffect)(() => {
        if (state.results) {
            updatesSubscription.current = pubsub_js_1.default.subscribe(`${PubSub_1.SCTopicType.EVENT}.${PubSub_1.SCGroupEventType.DELETE}`, onDeleteEventHandler);
        }
        return () => {
            updatesSubscription.current && pubsub_js_1.default.unsubscribe(updatesSubscription.current);
        };
    }, [state.results]);
    // RENDER
    if (!eventsEnabled || (state.initialized && state.count === 0)) {
        return (0, jsx_runtime_1.jsx)(HiddenPlaceholder_1.default, {});
    }
    if (!state.initialized || state.isLoadingNext) {
        return (0, jsx_runtime_1.jsx)(Skeleton_1.default, {});
    }
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: classes.root }, rest, { children: [(0, jsx_runtime_1.jsx)(system_1.Box, Object.assign({ className: classes.titleWrapper }, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h5" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.myEventsWidget.title", defaultMessage: "ui.myEventsWidget.title" }) })) })), (0, jsx_runtime_1.jsx)(Event_1.default, { event: state.results[eventIndex], template: event_1.SCEventTemplateType.DETAIL, actions: (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {}), elevation: 0, square: true }), (0, jsx_runtime_1.jsxs)(material_1.CardActions, Object.assign({ className: classes.actions }, { children: [(0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ size: "small", disabled: eventIndex === 0, className: classes.arrows, onClick: handlePrev }, { children: (0, jsx_runtime_1.jsx)(material_1.Icon, { children: "chevron_left" }) })), (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ href: scRoutingContext.url(react_core_1.SCRoutes.EVENTS_ROUTE_NAME, {}), 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.myEventsWidget.showAll", defaultMessage: "ui.myEventsWidget.showAll" }) })) })), (0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ size: "small", disabled: eventIndex === state.count - 1, className: classes.arrows, onClick: handleNext }, { children: (0, jsx_runtime_1.jsx)(material_1.Icon, { children: "chevron_right" }) }))] }))] })));
}
exports.default = MyEventsWidget;
