<!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 testImage()
{
    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;

    var index = 20;
    assert_true(data[index] < 100);
    assert_true(data[index + 1] < 100);
    assert_true(data[index + 2] < 100);

    index = 80;
    assert_true(data[index] > 200);
    assert_true(data[index + 1] > 200);
    assert_true(data[index + 2] > 200);

    index += 80;
    assert_true(data[index] > 200);
    assert_true(data[index + 1] > 200);
    assert_true(data[index + 2] < 100);
}

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

    return navigator.mediaDevices.getUserMedia({ video: true, audio: true}).then((stream) => {
        return new Promise((resolve, reject) => {
            var count = 0;
            var channel;
            var remoteStream;
            createConnections((firstConnection) => {
                firstConnection.addTrack(stream.getVideoTracks()[0], stream);
                firstConnection.addTrack(stream.getAudioTracks()[0], stream);
                channel = firstConnection.createDataChannel("test");
            }, (secondConnection) => {
                secondConnection.ontrack = (trackEvent) => {
                    if (count++ === 0)
                        return;
                    channel.onopen = () => channel.send("test");
                    remoteStream = trackEvent.streams[0];
                };
                secondConnection.ondatachannel = (event) => {
                    event.channel.onmessage = (event) => {
                        assert_equals(event.data, "test");
                        resolve(remoteStream);
                    }
                }
            });
            setTimeout(() => reject("Test timed out"), 5000);
        });
    }).then((stream) => {
        video.srcObject = stream;
        return video.play();
    }).then(() => {
        testImage();
    });
}, "Audio/Video with data channel");
        </script>
    </body>
</html>
