import { JitsiMeeting } from '@jitsi/react-sdk'
import { JITSI_DOMAIN } from '../../background/constants'
import { UserInfo } from './types'
import curry from 'just-curry-it'
import {
  ConferenceData,
  displayNameChangeListener,
  displayNameChangeListenerWrapper,
  videoConferenceJoinedListener,
} from '../../background/jitsi/eventListeners'
import useJitsiEventCapture from '../../hooks/useJitsiEventCapture'

interface Props {
  roomName: string
  userInfo: UserInfo
  conferenceData: ConferenceData | undefined
  setConferenceData: (newData: ConferenceData) => void
}

function JitsiEntrypoint({ roomName, userInfo, conferenceData, setConferenceData }: Props) {
  const { setDisplayNameChangeEvent } = useJitsiEventCapture(
    curry(displayNameChangeListener)(conferenceData)(setConferenceData)
  )

  return (
    <JitsiMeeting
      domain={JITSI_DOMAIN}
      roomName={roomName}
      configOverwrite={{
        startWithAudioMuted: true,
        disableModeratorIndicator: true,
        startScreenSharing: true,
        enableEmailInStats: false,
        prejoinConfig: { enabled: false },
      }}
      interfaceConfigOverwrite={{}}
      userInfo={userInfo}
      onApiReady={(externalApi) => {
        externalApi.addEventListener(
          'videoConferenceJoined',
          curry(videoConferenceJoinedListener)(setConferenceData)
        )
        externalApi.addEventListener(
          'displayNameChange',
          curry(displayNameChangeListenerWrapper)(setDisplayNameChangeEvent)
        )
      }}
      getIFrameRef={(iframeRef) => {
        iframeRef.style.height = '100%'
        iframeRef.style.width = '100%'
      }}
    />
  )
}

export default JitsiEntrypoint
