<!DOCTYPE html>
<html>
    <head>
        <script src="../../resources/js-test-pre.js"></script>
    </head>
    <body>
        <script>
            description("Tests RTCPeerConnection onnegotiationneeded.");

            let stream;
            let pc, remotePC;
            let audioSender;

            async function negotiate()
            {
                const offer = await pc.createOffer();
                await pc.setLocalDescription(offer);
                await remotePC.setRemoteDescription(offer);
                const answer = await remotePC.createAnswer();
                await pc.setRemoteDescription(answer);
            }

            function error()
            {
                testFailed('Stream generation failed.');
                finishJSTest();
            }

            async function onNegotiationNeeded(event)
            {
                testPassed('onNegotiationNeeded was called when a track was added.');
                await negotiate();
                removeTrack();
            }

            async function onNegotiationNeeded2(event)
            {
                testPassed('onNegotiationNeeded2 was called when a track was removed.');
                await negotiate();
                addTrack();
            }

            function onNegotiationNeeded3(event)
            {
                testPassed('onNegotiationNeeded3 was called when a track was added.');
                finishJSTest();
            }

            async function gotStream(s)
            {
                testPassed('Got a stream.');
                stream = s;

                pc = new RTCPeerConnection({iceServers:[{urls:'stun:foo.com'}]});
                remotePC = new RTCPeerConnection({iceServers:[{urls:'stun:foo.com'}]});
                pc.onnegotiationneeded = onNegotiationNeeded;

                audioSender = pc.addTrack(stream.getAudioTracks()[0], stream);
            }

            function removeTrack()
            {
                pc.onnegotiationneeded = onNegotiationNeeded2;
                pc.removeTrack(audioSender);
            }

            function addTrack()
            {
                pc.onnegotiationneeded = onNegotiationNeeded3;
                pc.addTrack(stream.getVideoTracks()[0], stream);
            }

            if (window.testRunner)
                testRunner.setUserMediaPermission(true);
            else {
                debug("This test can not be run without the testRunner");
                finishJSTest();
            }

            navigator.mediaDevices.getUserMedia({audio:true, video:true}).then(gotStream).catch(error);

            window.jsTestIsAsync = true;
            window.successfullyParsed = true;
        </script>
        <script src="../../resources/js-test-post.js"></script>
    </body>
</html>
