import { useLocalMedia, useLocalVirtualBackgrounds } from '../../store'

export const useJoinPage = (videoEnabledByDefault?: boolean, audioEnabledByDefault?: boolean) => {
  const {
    localAudioStream,
    localVideoStream,
    videoStreamIsLoading,
    currentVideoDeviceId,
    toggleLocalAudioStream,
    toggleLocalVideoStream,
    selectAudioDevice,
    selectVideoDevice,
  } = useLocalMedia(videoEnabledByDefault, audioEnabledByDefault)

  const selectedAudioDeviceSettings = localAudioStream?.mediaStreamTrack?.getSettings()
  const selectedVideoDeviceSettings = localVideoStream?.mediaStreamTrack?.getSettings()

  const { currentVirtualBackground, virtualBackgroundStream, changeVirtualBackground, stopLocalVirtualBackground } =
    useLocalVirtualBackgrounds()

  const afterJoinCleanUp = () => {
    localAudioStream && toggleLocalAudioStream()
    localVideoStream && toggleLocalVideoStream()
    currentVirtualBackground && stopLocalVirtualBackground()
  }

  return {
    localMedia: {
      localAudioStream,
      localVideoStream,
      currentVirtualBackground,
      virtualBackgroundStream,
      selectedAudioDeviceSettings,
      selectedVideoDeviceSettings,
      videoStreamIsLoading,
      currentVideoDeviceId,
      toggleLocalAudioStream,
      toggleLocalVideoStream,
      changeVirtualBackground,
      stopLocalVirtualBackground,
      selectAudioDevice,
      selectVideoDevice,
    },
    afterJoinCleanUp,
  }
}
