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

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

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

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

  const videoStream = localVideoStream || virtualBackgroundStream
  const { type: virtualBackgroundType, url: virtualBackgroundUrl } = currentVirtualBackground ?? {}
  const localMediaJoinOptions = {
    audioDeviceSettings: localAudioStream && currentAudioDeviceId ? { deviceId: currentAudioDeviceId } : undefined,
    videoDeviceSettings: videoStream && currentVideoDeviceId ? { deviceId: currentVideoDeviceId } : undefined,
    virtualBackground: virtualBackgroundType ?? null,
    virtualBackgroundConfig: virtualBackgroundUrl ? { backgroundImageUrl: virtualBackgroundUrl } : undefined,
  }

  return {
    localMedia: {
      localAudioStream,
      localVideoStream,
      currentVirtualBackground,
      availableVirtualBackgrounds,
      virtualBackgroundStream,
      currentAudioDeviceId,
      currentVideoDeviceId,
      toggleLocalAudioStream,
      toggleLocalVideoStream,
      changeVirtualBackground,
      stopLocalVirtualBackground,
      selectAudioDevice,
      selectVideoDevice,
      localMediaJoinOptions,
    },
    afterJoinCleanUp,
  }
}
