"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 constants_1 = require("./constants");
const components_react_1 = require("@livekit/components-react");
const react_1 = require("react");
const RecordingIndicator_1 = tslib_1.__importDefault(require("./RecordingIndicator"));
const components_core_1 = require("@livekit/components-core");
const constants_2 = require("../constants");
const react_intl_1 = require("react-intl");
const classes = {
    root: `${constants_1.PREFIX}-root`,
    title: `${constants_1.PREFIX}-title`,
    content: `${constants_1.PREFIX}-content`,
    endConferenceWrap: `${constants_1.PREFIX}-end-conference-wrap`,
    btnBackHome: `${constants_1.PREFIX}-btn-back-home`,
    actions: `${constants_1.PREFIX}-actions`,
    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 LiveStreamVideoConference component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {LiveStreamVideoConference} from '@selfcommunity/react-ui';
 ```

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCLiveStreamForm-root|Styles applied to the root element.|

 * @param inProps
 */
function LiveStreamVideoConference(inProps) {
    //PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { className, liveStream, handleOnLeaveRoom, userChoices = components_core_1.defaultUserChoices, connectionDetails = {}, LiveKitRoomComponentsProps = {
    /* simulateParticipants: true */
    }, startConferenceEndContent, endConferenceEndContent, options = constants_2.defaultVideoOptions } = props, rest = tslib_1.__rest(props, ["className", "liveStream", "handleOnLeaveRoom", "userChoices", "connectionDetails", "LiveKitRoomComponentsProps", "startConferenceEndContent", "endConferenceEndContent", "options"]);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    const scRoutingContext = (0, react_core_1.useSCRouting)();
    const { preferences, features } = (0, react_core_1.useSCPreferences)();
    // Passphrase
    // const e2eePassphrase = typeof window !== 'undefined' && decodePassphrase(location.hash.substring(1));
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    // const worker = typeof window !== 'undefined' && e2eePassphrase && new Worker(new URL('livekit-client/e2ee-worker', import.meta.url));
    // const e2eeEnabled = !!(e2eePassphrase && worker);
    // const keyProvider = new ExternalE2EEKeyProvider();
    const [e2eeSetupComplete, setE2eeSetupComplete] = (0, react_1.useState)(true);
    const [liveActive, setLiveActive] = (0, react_1.useState)(true);
    const [error, setError] = (0, react_1.useState)(null);
    /* const liveStreamRoomMaxParticipants = useMemo(
          () =>
              preferences &&
              SCPreferences.CONFIGURATIONS_LIVE_STREAM_MAX_PARTICIPANTS in preferences &&
              preferences[SCPreferences.CONFIGURATIONS_LIVE_STREAM_MAX_PARTICIPANTS].value,
          [preferences]
      ); */
    // Room options
    /* const roomOptions = useMemo((): RoomOptions => {
      let videoCodec: VideoCodec | undefined = options.codec ? options.codec : defaultVideoOptions.codec;
      if (e2eeEnabled && (videoCodec === 'av1' || videoCodec === 'vp9')) {
        videoCodec = undefined;
      }
      return {
        // emptyTimeout: 3 * 60, // 3 minutes
        // maxParticipants: liveStreamRoomMaxParticipants,
        videoCaptureDefaults: {
          deviceId: userChoices.videoDeviceId ?? undefined,
          resolution: options.hq ? VideoPresets.h2160 : VideoPresets.h720
        },
        publishDefaults: {
          dtx: false,
          videoSimulcastLayers: options.hq ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216],
          red: !e2eeEnabled,
          videoCodec
        },
        audioCaptureDefaults: {
          deviceId: userChoices.audioDeviceId ?? undefined
        },
        adaptiveStream: {pixelDensity: 'screen'},
        dynacast: true,
        e2ee: e2eeEnabled
          ? {
              keyProvider,
              worker
            }
          : undefined
      };
    }, [liveStreamRoomMaxParticipants, userChoices, options.hq, options.codec]); */
    // Create room - only initial
    /* const room = useMemo(() => {
      const room = new Room();
      return new Room(roomOptions);
    }, [liveStreamRoomMaxParticipants]); */
    const connectOptions = (0, react_1.useMemo)(() => {
        return {
            autoSubscribe: true
        };
    }, []);
    /* useEffect(() => {
      if (room) {
        if (e2eeEnabled) {
          keyProvider
            .setKey(decodePassphrase(e2eePassphrase))
            .then(() => {
              room.setE2EEEnabled(true).catch((e) => {
                if (e instanceof DeviceUnsupportedError) {
                  alert(
                    `You're trying to join an encrypted meeting, but your browser does not support it. Please update it to the latest version and try again.`
                  );
                  console.error(e);
                } else {
                  throw e;
                }
              });
            })
            .then(() => {
              setE2eeSetupComplete(true);
              setLiveActive(true);
            });
        } else {
          setE2eeSetupComplete(true);
          setLiveActive(true);
        }
      }
    }, [e2eeEnabled, room, e2eePassphrase]); */
    // HANDLERS
    /**
     * Handle on leave
     */
    const handleOnLeave = (0, react_1.useCallback)(() => {
        setLiveActive(false);
        handleOnLeaveRoom === null || handleOnLeaveRoom === void 0 ? void 0 : handleOnLeaveRoom();
    }, [handleOnLeaveRoom]);
    /**
     * Handle on error
     */
    const handleError = (0, react_1.useCallback)((error) => {
        console.error(error);
        setError(`Encountered an unexpected error, check the console logs for details: ${error.message}`);
        setLiveActive(false);
    }, []);
    /**
     * Handle encryption error
     */
    const handleEncryptionError = (0, react_1.useCallback)((error) => {
        console.error(error);
        setError(`Encountered an unexpected encryption error, check the console logs for details: ${error.message}`);
        setLiveActive(false);
    }, []);
    /**
     * User must be authenticated
     */
    if (!scUserContext.user || !connectionDetails) {
        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: liveActive && !error ? ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, jsx_runtime_1.jsxs)(components_react_1.LiveKitRoom, Object.assign({ connect: Boolean(e2eeSetupComplete && liveActive), token: connectionDetails['participantToken'], serverUrl: connectionDetails['serverUrl'], connectOptions: connectOptions, video: userChoices.videoEnabled, audio: userChoices.audioEnabled, onDisconnected: handleOnLeave, onEncryptionError: handleEncryptionError, onError: handleError }, LiveKitRoomComponentsProps, { children: [(0, jsx_runtime_1.jsx)(components_react_1.VideoConference, { chatMessageFormatter: components_react_1.formatChatMessageLinks }), (0, jsx_runtime_1.jsx)(components_react_1.Chat, {}), (0, jsx_runtime_1.jsx)(RecordingIndicator_1.default, {}), (0, jsx_runtime_1.jsx)(components_react_1.ConnectionState, {})] })) })) : ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: error ? ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.endConferenceWrap }, { children: [startConferenceEndContent, error, endConferenceEndContent] }))) : liveActive === false ? ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.endConferenceWrap }, { children: [startConferenceEndContent, (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h5" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.liveStreamRoom.conference.end", defaultMessage: "ui.liveStreamRoom.conference.end" }) })), (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ variant: "contained", color: "secondary", component: react_core_1.Link, to: '/', className: classes.btnBackHome }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.liveStreamRoom.button.backHome", defaultMessage: "ui.liveStreamRoom.button.backHome" }) })), endConferenceEndContent] }))) : ((0, jsx_runtime_1.jsx)(material_1.CircularProgress, {})) })) })));
}
exports.default = LiveStreamVideoConference;
