import React, { useEffect } from 'react'
import { DOMAttachableStream } from '@zocks-communications/client-sdk-js'
import { useAudio } from './hooks'
import { useSelectMediaDevice } from '../DeviceSelectButton'

export const Audio: React.FC<{ audioStream: DOMAttachableStream | null }> = ({ audioStream }) => {
  const { audioRef } = useAudio(audioStream)
  const { selectedMediaDeviceId } = useSelectMediaDevice('audiooutput')

  useEffect(() => {
    // @ts-ignore
    if (audioRef.current?.setSinkId) {
      // @ts-ignore
      audioRef.current.setSinkId(selectedMediaDeviceId)
    }
  }, [audioRef, selectedMediaDeviceId])

  return audioStream && <audio ref={audioRef} data-testid='audioElement' />
}
