import { ReactNode, useEffect } from 'react';
import { IMicrophoneAudioTrack, LocalAudioTrack, LocalAudioTrackProps, MaybePromiseOrNull } from 'agora-rtc-react';
import { useAwaited } from '../../../../utils/agora/tools';

interface MicrophoneAudioTrackProps extends LocalAudioTrackProps {
    /**
     * A microphone audio track which can be created by `createMicrophoneAudioTrack()`.
     */
    readonly track?: MaybePromiseOrNull<IMicrophoneAudioTrack>;
    /**
     * Device ID, which can be retrieved by calling `getDevices()`.
     */
    readonly deviceId?: string;

    readonly children?: ReactNode;
}

export const MicrophoneAudioTrack = ({
    track: maybeTrack,
    deviceId,
    ...props
}: MicrophoneAudioTrackProps) => {
    const track = useAwaited(maybeTrack);

    useEffect(() => {
        if (track && deviceId != null) {
            track.setDevice(deviceId).catch(console.warn);
        }
    }, [deviceId, track]);

    return <LocalAudioTrack track={maybeTrack} {...props} />;
};
