"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLivestreamCheck = void 0;
const react_1 = require("react");
const api_services_1 = require("@selfcommunity/api-services");
const components_react_1 = require("@livekit/components-react");
const LiveStreamProvider_1 = require("./LiveStreamProvider");
const notistack_1 = require("notistack");
const react_intl_1 = require("react-intl");
const react_core_1 = require("@selfcommunity/react-core");
const constants_1 = require("../constants");
const livekit_client_1 = require("livekit-client");
/**
 * Custom hook for monitoring livestream.
 * @param {number} warningThreshold
 * @param showWarnings
 * @param performDisconnect
 */
function useLivestreamCheck(warningThreshold = constants_1.WARNING_THRESHOLD_EXPIRING_SOON, showWarnings = true, performDisconnect = true) {
    // STATE
    const [timeRemaining, setTimeRemaining] = (0, react_1.useState)(60);
    const [isExpiringSoon, setIsExpiringSoon] = (0, react_1.useState)(false);
    const [isExpired, setIsExpired] = (0, react_1.useState)(false);
    const intervalRef = (0, react_1.useRef)(null);
    // HOOKS
    const scUserContext = (0, react_core_1.useSCUser)();
    const participants = (0, components_react_1.useParticipants)({
        updateOnlyOn: [
            livekit_client_1.RoomEvent.ParticipantConnected,
            livekit_client_1.RoomEvent.ParticipantDisconnected,
            livekit_client_1.RoomEvent.ConnectionStateChanged,
            livekit_client_1.RoomEvent.Connected,
            livekit_client_1.RoomEvent.Disconnected,
            livekit_client_1.RoomEvent.TrackSubscribed,
            livekit_client_1.RoomEvent.TrackUnsubscribed
        ]
    });
    const { liveStream } = (0, LiveStreamProvider_1.useLiveStream)();
    const { buttonProps } = (0, components_react_1.useDisconnectButton)({});
    const { enqueueSnackbar } = (0, notistack_1.useSnackbar)();
    const __DEBUG = (0, react_1.useRef)(true);
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    /**
     * fetchLivestreamStatus
     */
    const fetchLivestreamStatus = () => {
        api_services_1.LiveStreamApiClient.getMonthlyDuration()
            .then((r) => {
            setTimeRemaining(r.remaining_minutes);
            if (r.remaining_minutes > 0 && r.remaining_minutes <= warningThreshold) {
                setIsExpiringSoon(true);
                if (!isExpiringSoon && !isExpired && liveStream.host.id === scUserContext.user.id && showWarnings) {
                    __DEBUG && console.log('Warning: ');
                    enqueueSnackbar(intl.formatMessage({ id: 'ui.liveStreamRoom.check.fewMinutesRemaining', defaultMessage: 'ui.liveStreamRoom.check.fewMinutesRemaining' }), {
                        variant: 'warning',
                        autoHideDuration: 30000
                    });
                }
            }
            else if (r.remaining_minutes <= 0) {
                __DEBUG && console.log('Livestream  ');
                setIsExpired(true);
                clearInterval(intervalRef.current);
            }
            else if (isExpiringSoon) {
                setIsExpiringSoon(false);
            }
        })
            .catch((error) => {
            console.error('Error fetching live status:', error);
        });
    };
    /**
     * Check live
     */
    const check = (0, react_1.useCallback)(() => {
        if (__DEBUG) {
            console.log('Checking live status');
            console.log(participants.length);
            console.log('isExpiringSoon: ', isExpiringSoon);
            console.log('isExpired: ', isExpired);
            console.log('Checking participants...', participants.length);
            console.log(participants);
        }
        if (participants.length <= 1) {
            isExpiringSoon ? setIsExpired(true) : setIsExpiringSoon(true);
            if (!isExpiringSoon && !isExpired && showWarnings) {
                enqueueSnackbar(intl.formatMessage({ id: 'ui.liveStreamRoom.check.youAreAloneInTheRoom', defaultMessage: 'ui.liveStreamRoom.check.youAreAloneInTheRoom' }), { variant: 'warning', autoHideDuration: 7000 });
            }
            else if (isExpired && performDisconnect) {
                // Leave the room
                __DEBUG && console.log('Leave the room: no participants');
                buttonProps.onClick();
            }
            return;
        }
        else if (isExpiringSoon) {
            setIsExpiringSoon(false);
        }
        __DEBUG && console.log('Checking live speaker...');
        const speaker = participants.find((pt) => {
            return pt.name === liveStream.host.username;
        });
        if (!speaker) {
            isExpiringSoon ? setIsExpired(true) : setIsExpiringSoon(true);
            if (!isExpiringSoon && !isExpired && liveStream.host.id !== scUserContext.user.id && showWarnings) {
                enqueueSnackbar(intl.formatMessage({ id: 'ui.liveStreamRoom.check.hostMissing', defaultMessage: 'ui.liveStreamRoom.check.hostMissing' }), {
                    variant: 'warning',
                    autoHideDuration: 7000
                });
            }
            else if (isExpired && performDisconnect) {
                // Leave the room
                __DEBUG && console.log('Leave the room: no host');
                buttonProps.onClick();
            }
        }
        else if (isExpiringSoon) {
            setIsExpiringSoon(false);
        }
        __DEBUG && console.log('Checking live status resources...');
        fetchLivestreamStatus();
    }, [isExpired, isExpiringSoon, buttonProps, participants]);
    (0, react_1.useEffect)(() => {
        intervalRef.current = setInterval(check, constants_1.LIVE_CHECKING_INTERVAL * 60000);
        return () => intervalRef.current && clearInterval(intervalRef.current);
    }, [isExpired, isExpiringSoon, participants]);
    return { timeRemaining, isExpiringSoon, isExpired };
}
exports.useLivestreamCheck = useLivestreamCheck;
