<!DOCTYPE HTML>
<html>
    <body>
        <div id="console">

        <script>

            if (window.testRunner) {
                testRunner.waitUntilDone();
                testRunner.dumpChildFramesAsText(true);
            }

            const params = new URL(window.location.href).search.substr(1).split(';');
            const fail = (msg) => { return `<span><span class="fail">FAIL</span> ${msg}</span>` }
            const success = (msg) => { return `<span><span class="fail">PASS</span> ${msg}</span>` }
            const debug = (msg) => {
                let span = document.createElement("span");
                span.innerHTML = msg + '<br>';
                document.getElementById("console").appendChild(span);
            }

            const mode = params[0];
            function finish(error, stream)
            {
                if (mode === "succeed") {
                    if (stream)
                        debug(success("getUserMedia succeeded"));
                    else
                        debug(fail(`getUserMedia should have succeeded but failed with error "${error}"`));
                } else {
                    if (error)
                        debug(success(`getUserMedia failed with error: "${error}"`));
                    else
                        debug(fail(`getUserMedia should have succeeded, but failed with error "${error}"`));
                }

                debug('<br><span class="pass">TEST COMPLETE</span>');
                if (window.testRunner)
                    testRunner.notifyDone();
            }

            debug(`URL: ${window.location.href}`);

            const depth = params[1];
            if (depth > 1) {
                let iframe = document.createElement("iframe");
                let url = window.location.href.split('?')[0];
                iframe.src = `${url}?${mode};${depth - 1}`;
                document.body.appendChild(iframe);
            } else {
                debug("");
                navigator.mediaDevices.getUserMedia({audio:true})
                    .then(stream => { finish(null, stream); })
                    .catch(err =>  { finish(err, null); });
            }
        </script>
    </body>
</html>
