import { useEffect } from 'react';
import { ICameraVideoTrack, LocalVideoTrack, LocalVideoTrackProps, MaybePromiseOrNull } from 'agora-rtc-react';
import { useAwaited } from '../../../../utils/agora/tools';

interface CameraVideoTrackProps extends LocalVideoTrackProps {
    /**
     * A camera video track which can be created by `createCameraVideoTrack()`.
     */
    readonly track?: MaybePromiseOrNull<ICameraVideoTrack>;
    /**
     * Device ID, which can be retrieved by calling `getDevices()`.
     */
    readonly deviceId?: string;
}

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

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

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