<!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>
        <script src ="routines.js"></script>
        <script>
function fingerprintFromSDP(sdp)
{
    var fingerprint;
    sdp.split("\r\n").forEach((line) => {
        if (line.startsWith("a=fingerprint"))
            fingerprint = line.substring(14);
    });
    return fingerprint;
}

function cnameFromSDP(sdp)
{
    var expression = new RegExp("^a=ssrc:(\\d+) cname:([\\w+/\\-@\\.\\{\\}]+).*$");

    var cname;
    sdp.split("\r\n").forEach((line) => {
        let match = line.match(expression);
        if (match)
            cname = match[2];
    });
    return cname;
}

promise_test((test) => {
    if (window.testRunner)
        testRunner.setUserMediaPermission(true);

    var offerFingerprint, answerFingerprint;
    var offerCName;
    return navigator.mediaDevices.getUserMedia({ video: true, audio: true}).then((stream) => {
        return new Promise((resolve, reject) => {
            createConnections((firstConnection) => {
                firstConnection.addTrack(stream.getVideoTracks()[0], stream);
            }, (secondConnection) => {
            }, {observeOffer : (offer) => {
                offerFingerprint = fingerprintFromSDP(offer.sdp);
                offerCName = cnameFromSDP(offer.sdp);
            }, observeAnswer: (answer) => {
                answerFingerprint = fingerprintFromSDP(answer.sdp);
                resolve();
            }});
            setTimeout(() => reject("Test timed out 1"), 2000);
        });
    }).then(() => {
        closeConnections();
        return navigator.mediaDevices.getUserMedia({ video: true, audio: true}).then((stream) => {
            return new Promise((resolve, reject) => {
                createConnections((firstConnection) => {
                    firstConnection.addTrack(stream.getVideoTracks()[0], stream);
                }, (secondConnection) => {
                }, {observeOffer : (offer) => {
                    assert_not_equals(fingerprintFromSDP(offer.sdp), offerFingerprint);
                    assert_not_equals(cnameFromSDP(offer.sdp), offerCName);
                }, observeAnswer: (answer) => {
                    assert_not_equals(fingerprintFromSDP(answer.sdp), answerFingerprint);
                    resolve();
                }});
                setTimeout(() => reject("Test timed out 2"), 2000);
            });
        });
    });
}, "Ensuring certificates and cnames are ephemerals");
        </script>
    </body>
</html>
