<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Testing replacing an audio track during a WebRTC call</title>
    <script src="../resources/testharness.js"></script>
    <script src="../resources/testharnessreport.js"></script>
    <script src ="routines.js"></script>
</head>
<body>
    <script>
    var sender;
    var remoteStream;
    var secondStream;
    var receivingConnection;
    promise_test((test) => {
        if (window.testRunner)
            testRunner.setUserMediaPermission(true);

        return navigator.mediaDevices.getUserMedia({ audio: { sampleRate: { exact: 48000 } } }).then((firstStream) => {
            return new Promise((resolve, reject) => {
                createConnections((firstConnection) => {
                    sender = firstConnection.addTrack(firstStream.getAudioTracks()[0], firstStream);
                }, (secondConnection) => {
                    receivingConnection = secondConnection;
                    secondConnection.ontrack = (trackEvent) => { resolve(trackEvent.streams[0]); };
                });
                setTimeout(() => reject("Test timed out"), 5000);
            });
        }).then((stream) => {
            remoteStream = stream;
         });
    }, "Starting an audio connection");

    promise_test(() => {
        if (receivingConnection.connectionState === "connected")
            return Promise.resolve();
        return new Promise((resolve, reject) => {
            receivingConnection.onconnectionstatechange = () => {
                if (receivingConnection.connectionState === "connected")
                    resolve();
            };
            setTimeout(() => reject("Test timed out"), 5000);
        });
    }, "Ensuring connection state is connected");

    promise_test(() => {
        return doHumAnalysis(remoteStream, true).then((result) => {
            assert_true(result, "heard hum 1");
        });
    }, "Ensuring mock audio source is received on the remote side");

    promise_test(() => {
        return navigator.mediaDevices.getUserMedia({ audio: { sampleRate: { exact: 48000 } } }).then((stream) => {
            secondStream = stream;
            return sender.replaceTrack(secondStream.getAudioTracks()[0], secondStream);
        }).then(() => {
            assert_true(sender.track === secondStream.getAudioTracks()[0]);
            return waitFor(500);
        });
    }, "Using replaceTrack for audio");

    promise_test(() => {
        return doHumAnalysis(remoteStream, true).then((results) => {
            assert_true(results, "heard hum 2");
        });
    }, "Ensuring remote audio gets the replacing track data");
    </script>
</body>
</html>
