<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="../../resources/testharness.js"></script>
    <script src="../../resources/testharnessreport.js"></script>
</head>
<body>
    <video id="video"></video>
    <script>
    let setup = async (test) => {
        if (!window.testRunner)
            return Promise.reject("test requires internal API");

        test.add_cleanup(() => {
            testRunner.resetMockMediaDevices();
            testRunner.setMockCameraOrientation(0);
        });
    }

    async function getSettingsBeforeAndAfterRotation(deviceId)
    {
        testRunner.setMockCameraOrientation(0);

        const stream = await navigator.mediaDevices.getUserMedia({ video: { deviceId } });
        video.srcObject = stream;
        await video.play();

        const track = stream.getVideoTracks()[0];
        const initialSettings = track.getSettings();

        video.srcObject = null;

        testRunner.setMockCameraOrientation(90);
        await new Promise(resolve => setTimeout(resolve, 100));

        video.srcObject = stream;
        await video.play();

        return [initialSettings, track.getSettings()];
    }

     promise_test(async (test) => {
         await setup(test);
 
         const results = await getSettingsBeforeAndAfterRotation("default");
 
         assert_equals(results[0].facingMode, "user");
         assert_equals(results[0].width, 640, "initial width");
         assert_equals(results[0].height, 480, "initial height");
         assert_equals(results[1].width, 480, "final width");
         assert_equals(results[1].height, 640, "final height");
     }, "Width and height before and after rotation with default device");

    promise_test(async (test) => {
        await setup(test);

        testRunner.addMockCameraDevice("myCamera", "my new camera", { facingMode: "unknown", fillColor: "green" });
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });

        const devices = await navigator.mediaDevices.enumerateDevices();
        let deviceId = "";
        devices.forEach(device => {
            if (device.label == "my new camera")
                deviceId = device.deviceId;
        });
        stream.getVideoTracks()[0].stop();

        const results = await getSettingsBeforeAndAfterRotation(deviceId);

         assert_equals(results[0].facingMode, undefined);
        assert_equals(results[0].width, 640, "initial width");
        assert_equals(results[0].height, 480, "initial height");
        assert_equals(results[1].width, 640, "final width");
        assert_equals(results[1].height, 480, "final height");
    }, "Width and height before and after rotation with new device");
    </script>
</body>
</html>
