<!DOCTYPE html>

<html>
    <head>
        <script src="../../resources/js-test-pre.js"></script>
    </head>
    <body>
        <script>
            description("Test RTCPeerConnection 'icecandidate' event and gathering done");

            if (window.internals)
                internals.useMockRTCPeerConnectionFactory("ICECandidates");

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

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

            var candidates = [];
            var shouldDoChecking = false;
            var reachedEndOfCandidates = false;
            pc.onicecandidate = function (evt) {
                candidates.push(evt.candidate);
                if (!evt.candidate)
                    reachedEndOfCandidates = true;
                checkCandidates();
            };

            function checkCandidates() {
              if (!shouldDoChecking || !reachedEndOfCandidates)
                return;
              for (candidate of candidates) {
                if (candidate) {
                    testPassed("Got candidate");
                    shouldBeTrue("candidate instanceof RTCIceCandidate");
                    shouldBe("candidate.sdpMLineIndex", "0");
                    shouldBe("candidate.sdpMid", "pc.getTransceivers()[0].mid");
                    testPassed(`candidate.candidate: ${candidate.candidate}`);
                } else {
                    testPassed("Got end of candidates");
                    shouldBeNull("candidate");
                }
              }
              finishJSTest();
            }

            navigator.mediaDevices.getUserMedia({ "video": true }).then(function (stream) {
                pc.addTrack(stream.getTracks()[0], stream);
                return pc.createOffer();
            }).then(function (offer) {
                return pc.setLocalDescription(offer);
            }).then(function () {
                testPassed("Local description set");
                testPassed("End of test promise chain");
                if (window.internals)
                    window.internals.emulateRTCPeerConnectionPlatformEvent(pc, "dispatch-fake-ice-candidates");
                shouldDoChecking = true;
                checkCandidates();
            }).catch(function (error) {
                testFailed("Error in promise chain: " + error);
                finishJSTest();
            });

            window.jsTestIsAsync = true;
            window.successfullyParsed = true;

        </script>
        <script src="../../resources/js-test-post.js"></script>
    </body>
</html>
