import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Box, Button, CircularProgress, Typography } from '@mui/material';
import { styled } from '@mui/material/styles';
import { useThemeProps } from '@mui/system';
import { Link, useSCPreferences, useSCRouting, useSCUser } from '@selfcommunity/react-core';
import classNames from 'classnames';
import { PREFIX } from './constants';
import { Chat, ConnectionState, formatChatMessageLinks, LiveKitRoom, VideoConference } from '@livekit/components-react';
import { useCallback, useMemo, useState } from 'react';
import RecordingIndicator from './RecordingIndicator';
import { defaultUserChoices } from '@livekit/components-core';
import { defaultVideoOptions } from '../constants';
import { FormattedMessage } from 'react-intl';
const classes = {
    root: `${PREFIX}-root`,
    title: `${PREFIX}-title`,
    content: `${PREFIX}-content`,
    endConferenceWrap: `${PREFIX}-end-conference-wrap`,
    btnBackHome: `${PREFIX}-btn-back-home`,
    actions: `${PREFIX}-actions`,
    error: `${PREFIX}-error`
};
const Root = styled(Box, {
    name: 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
 */
export default function LiveStreamVideoConference(inProps) {
    //PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, liveStream, handleOnLeaveRoom, userChoices = defaultUserChoices, connectionDetails = {}, LiveKitRoomComponentsProps = {
    /* simulateParticipants: true */
    }, startConferenceEndContent, endConferenceEndContent, options = defaultVideoOptions } = props, rest = __rest(props, ["className", "liveStream", "handleOnLeaveRoom", "userChoices", "connectionDetails", "LiveKitRoomComponentsProps", "startConferenceEndContent", "endConferenceEndContent", "options"]);
    // CONTEXT
    const scUserContext = useSCUser();
    const scRoutingContext = useSCRouting();
    const { preferences, features } = 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] = useState(true);
    const [liveActive, setLiveActive] = useState(true);
    const [error, setError] = 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 = 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 = useCallback(() => {
        setLiveActive(false);
        handleOnLeaveRoom === null || handleOnLeaveRoom === void 0 ? void 0 : handleOnLeaveRoom();
    }, [handleOnLeaveRoom]);
    /**
     * Handle on error
     */
    const handleError = 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 = 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 _jsx(CircularProgress, {});
    }
    /**
     * Renders root object
     */
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: liveActive && !error ? (_jsx(_Fragment, { children: _jsxs(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: [_jsx(VideoConference, { chatMessageFormatter: formatChatMessageLinks }), _jsx(Chat, {}), _jsx(RecordingIndicator, {}), _jsx(ConnectionState, {})] })) })) : (_jsx(_Fragment, { children: error ? (_jsxs(Box, Object.assign({ className: classes.endConferenceWrap }, { children: [startConferenceEndContent, error, endConferenceEndContent] }))) : liveActive === false ? (_jsxs(Box, Object.assign({ className: classes.endConferenceWrap }, { children: [startConferenceEndContent, _jsx(Typography, Object.assign({ variant: "h5" }, { children: _jsx(FormattedMessage, { id: "ui.liveStreamRoom.conference.end", defaultMessage: "ui.liveStreamRoom.conference.end" }) })), _jsx(Button, Object.assign({ variant: "contained", color: "secondary", component: Link, to: '/', className: classes.btnBackHome }, { children: _jsx(FormattedMessage, { id: "ui.liveStreamRoom.button.backHome", defaultMessage: "ui.liveStreamRoom.button.backHome" }) })), endConferenceEndContent] }))) : (_jsx(CircularProgress, {})) })) })));
}
