<!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>
        <canvas id="canvas" width="640" height="480"></canvas>
        <script src ="routines.js"></script>
        <script>
video = document.getElementById("video");
canvas = document.getElementById("canvas");

function isVideoBlack()
{
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

    imageData = canvas.getContext('2d').getImageData(10, 325, 250, 1);
    data = imageData.data;
    for (var cptr = 0; cptr < canvas.width * canvas.height; ++cptr) {
        if (data[4 * cptr] || data[4 * cptr + 1] || data[4 * cptr + 2])
            return false;
    }
    return true;
}

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

    return navigator.mediaDevices.getUserMedia({ video: true}).then((localStream) => {
        return new Promise((resolve, reject) => {
            createConnections((firstConnection) => {
                firstConnection.addTrack(localStream.getVideoTracks()[0], localStream);
            }, (secondConnection) => {
                secondConnection.ontrack = (trackEvent) => { resolve(trackEvent.streams[0]); };
            });
            setTimeout(() => reject("Test timed out"), 5000);
        });
    }).then((remoteStream) => {
        video.srcObject = remoteStream;
        track = remoteStream.getVideoTracks()[0];
        return video.play();
    }).then(() => {
         assert_false(isVideoBlack());
    }).then(() => {
        track.enabled = false;
        return waitFor(500);
    }).then(() => {
        assert_true(isVideoBlack());
        track.enabled = true;
        return waitFor(500);
    }).then(() => {
        assert_false(isVideoBlack());
    });
}, "Incoming muted/unmuted video track");
        </script>
    </body>
</html>
