"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 react_core_1 = require("@selfcommunity/react-core");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const react_intl_1 = require("react-intl");
const constants_1 = require("./constants");
const components_react_1 = require("@livekit/components-react");
const react_1 = require("react");
const LiveStreamVideoConference_1 = tslib_1.__importDefault(require("./LiveStreamVideoConference"));
require("@livekit/components-styles");
const liveStream_1 = require("../../utils/liveStream");
const classes = {
    root: `${constants_1.PREFIX}-root`,
    content: `${constants_1.PREFIX}-content`,
    title: `${constants_1.PREFIX}-title`,
    description: `${constants_1.PREFIX}-description`,
    startPrejoinContent: `${constants_1.PREFIX}-start-prejoin-content`,
    preJoin: `${constants_1.PREFIX}-prejoin`,
    preJoinLoading: `${constants_1.PREFIX}-prejoin-loading`,
    prejoinLoader: `${constants_1.PREFIX}-prejoin-loader`,
    endPrejoinContent: `${constants_1.PREFIX}-end-prejoin-content`,
    conference: `${constants_1.PREFIX}-conference`,
    error: `${constants_1.PREFIX}-error`
};
const Root = (0, styles_1.styled)(material_1.Box, {
    name: constants_1.PREFIX,
    slot: 'Root'
})(({ theme }) => ({}));
/**
 *> API documentation for the Community-JS LiveStreamRoom component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {LiveStreamRoom} from '@selfcommunity/react-ui';
 ```

 #### Component Name
 The name `LiveStreamRoom` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCLiveStreamRoom-root|Styles applied to the root element.|
 |title|.SCLiveStreamRoom-title|Styles applied to the title element.|
 |description|.SCLiveStreamRoom-description|Styles applied to the description element.|
 |content|.SCLiveStreamRoom-content|Styles applied to the content.|
 |prejoin|.SCLiveStreamRoom-prejoin|Styles applied to the prejoin.|
 |conference|.SCLiveStreamRoom-conference|Styles applied to the conference.|
 |error|.SCLiveStreamRoom-error|Styles applied to the error elements.|

 * @param inProps
 */
function LiveStreamRoom(inProps) {
    var _a;
    //PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { className, liveStream = null, showPrejoinTitle = true, showPrejoinDescription = false, startPrejoinContent, endPrejoinContent, connectionDetailsEndpoint, presetConnectionDetails, presetPreJoinChoices, LiveStreamVideoConferenceComponentProps = {} } = props, rest = tslib_1.__rest(props, ["className", "liveStream", "showPrejoinTitle", "showPrejoinDescription", "startPrejoinContent", "endPrejoinContent", "connectionDetailsEndpoint", "presetConnectionDetails", "presetPreJoinChoices", "LiveStreamVideoConferenceComponentProps"]);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    const { preferences, features } = (0, react_core_1.useSCPreferences)();
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    // STATE
    const [preJoinChoices, setPreJoinChoices] = (0, react_1.useState)(presetPreJoinChoices);
    const [loading, setLoading] = (0, react_1.useState)(false);
    const preJoinDefaults = (0, react_1.useMemo)(() => {
        var _a;
        return {
            username: ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.username) || '',
            videoEnabled: true,
            audioEnabled: true
        };
    }, [scUserContext.user]);
    const [connectionDetails, setConnectionDetails] = (0, react_1.useState)(presetConnectionDetails);
    const liveStreamEnabled = true;
    /* const liveStreamEnabled = useMemo(
          () =>
              preferences &&
              features &&
              features.includes(SCFeatureName.LIVE_STREAM) &&
              SCPreferences.CONFIGURATIONS_LIVE_STREAM_ENABLED in preferences &&
              preferences[SCPreferences.CONFIGURATIONS_LIVE_STREAM_ENABLED].value,
          [preferences, features]
      ); */
    const canCreateLiveStream = (0, react_1.useMemo)(() => true /* scUserContext?.user?.permission?.create_livestream */, [(_a = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _a === void 0 ? void 0 : _a.permission]);
    const toggleAttrDisabledPrejoinActions = (0, react_1.useCallback)((disabled) => {
        const container = document.querySelector('.lk-prejoin');
        if (container) {
            const buttons = container.querySelectorAll('button.lk-button');
            buttons.forEach((button) => {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                button.disabled = disabled;
            });
        }
    }, []);
    // HANDLERS
    /**
     * Handle PreJoin Submit
     */
    const handlePreJoinSubmit = (0, react_1.useCallback)((values) => tslib_1.__awaiter(this, void 0, void 0, function* () {
        var _b;
        // eslint-disable-next-line no-constant-condition
        if ((liveStream || true) && connectionDetailsEndpoint) {
            setLoading(true);
            toggleAttrDisabledPrejoinActions(true);
            setPreJoinChoices(values);
            const url = new URL(connectionDetailsEndpoint, window.location.origin);
            url.searchParams.append('roomName', liveStream.roomName || (0, liveStream_1.generateRoomId)());
            url.searchParams.append('participantName', (_b = scUserContext.user) === null || _b === void 0 ? void 0 : _b.username);
            /* if (liveStream && liveStream.region) {
              url.searchParams.append('region', liveStream.region);
            } */
            const connectionDetailsResp = yield fetch(url.toString());
            const connectionDetailsData = yield connectionDetailsResp.json();
            setConnectionDetails(connectionDetailsData);
            toggleAttrDisabledPrejoinActions(false);
            setLoading(false);
        }
    }), [scUserContext.user, connectionDetailsEndpoint, setPreJoinChoices, setConnectionDetails]);
    /**
     * Handle PreJoin Error
     */
    const handlePreJoinError = (0, react_1.useCallback)((e) => console.error(e), []);
    /**
     * User must be authenticated
     */
    if (!scUserContext.user || !liveStreamEnabled || !canCreateLiveStream) {
        return (0, jsx_runtime_1.jsx)(material_1.CircularProgress, {});
    }
    /**
     * Renders root object
     */
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, rest, { children: (0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ className: classes.content, "data-lk-theme": "default" }, { children: connectionDetails === undefined || preJoinChoices === undefined ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [startPrejoinContent && (0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ className: classes.startPrejoinContent }, { children: startPrejoinContent })), (liveStream === null || liveStream === void 0 ? void 0 : liveStream.title) && ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ component: 'div', variant: "h5", className: classes.title }, { children: liveStream === null || liveStream === void 0 ? void 0 : liveStream.title }))), (liveStream === null || liveStream === void 0 ? void 0 : liveStream.description) && ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ component: 'div', variant: "body1", className: classes.description }, { children: liveStream === null || liveStream === void 0 ? void 0 : liveStream.description }))), (0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: (0, classnames_1.default)(classes.preJoin, { [classes.preJoinLoading]: loading }) }, { children: [(0, jsx_runtime_1.jsx)(components_react_1.PreJoin, { persistUserChoices: true, defaults: preJoinDefaults, onSubmit: handlePreJoinSubmit, onError: handlePreJoinError }), loading && ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.prejoinLoader }, { children: [(0, jsx_runtime_1.jsx)(material_1.CircularProgress, {}), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ component: 'div', variant: "body2" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.liveStreamRoom.connecting", defaultMessage: "ui.liveStreamRoom.connecting" }) }))] })))] })), (0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ className: classes.endPrejoinContent }, { children: endPrejoinContent }))] })) : ((0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ className: classes.conference }, { children: (0, jsx_runtime_1.jsx)(LiveStreamVideoConference_1.default, Object.assign({ connectionDetails: connectionDetails, userChoices: preJoinChoices, options: { codec: props.codec, hq: props.hq } }, LiveStreamVideoConferenceComponentProps)) }))) })) })));
}
exports.default = LiveStreamRoom;
