<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Testing basic video exchange from offerer to receiver</title>
        <script src="../resources/testharness.js"></script>
        <script src="../resources/testharnessreport.js"></script>
    </head>
    <body>
        <video id="video" autoplay></video>
        <script src ="routines.js"></script>
        <script>
promise_test((test) => {
    var remoteStream, newOffer, secondConnection;
    var testPromise;
    return navigator.mediaDevices.getUserMedia({audio: true, video: true}).then((stream) => {
        return new Promise((resolve, reject) => {
            createConnections((firstConnection) => {
                firstConnection.addTrack(stream.getAudioTracks()[0], stream);
                firstConnection.addTrack(stream.getVideoTracks()[0], stream);
            }, (connection) => {
                secondConnection = connection;
                secondConnection.ontrack = (trackEvent) => {
                    resolve(trackEvent.streams[0]);
                };
            });
            setTimeout(() => reject("Test timed out"), 5000);
        });
    }).then((stream) => {
        remoteStream = stream;
        video.srcObject = stream;
        return video.play();
    }).then(() => {
        testPromise = new Promise((resolve, reject) => {
            var count = 0;
            var callback = () => {
                if (++count === 2)
                    resolve();
            }
            setTimeout(() => { reject("onended callbacks took too long"); }, 5000);
            remoteStream.getAudioTracks()[0].onended = callback;
            remoteStream.getVideoTracks()[0].onended = callback;
        });
        secondConnection.close();
        return testPromise;
    }).then(() => {
        assert_true(secondConnection.getTransceivers()[0].stopped, "transceiver 1 should be stopped");
        assert_true(secondConnection.getTransceivers()[1].stopped, "transceiver 2 should be stopped");
    });
}, "Ensuring onended events are thrown when peer connection is closed");
        </script>
    </body>
</html>
