<!DOCTYPE html>
<html>
<head>
<script src="../resources/js-test.js"></script>
<script type="text/javascript" src="resources/audio-testing.js"></script>
</head>
<body>
<script>
description("Basic tests for decodeAudioData function.");

window.jsTestIsAsync = true;

var context = new AudioContext();

// decodeAudioData should reject the promise when arraybuffer parameter is null.
context.decodeAudioData(null, function(){}, function(){}).then(() => {
    testFailed("Passing a null array to AudioContext.decodeAudioData() did not throw");
}, (e) => {
    if (e.name == "TypeError")
        testPassed("Passing a null array to AudioContext.decodeAudioData() threw a TypeError");
    else
        testFailed("Passing a null array to AudioContext.decodeAudioData() threw a " + e.name + " instead of a TypeError");
});

var decodeCaseArray = [{url: "resources/media/24bit-44khz.wav", result: true},
                       {url: "resources/media/128kbps-44khz.mp3", result: true},
                       {url: "resources/media/vbr-128kbps-44khz.m4a", result: true},
                       {url: "resources/media/invalid-audio-file.txt", result: false}];

function runDecodeTest(index) {
    if (index >= decodeCaseArray.length) {
        finishJSTest();
        return;
    }

    var request = new XMLHttpRequest();
    request.open("GET", decodeCaseArray[index].url, true);
    request.responseType = "arraybuffer";

    request.onload = function() {
        context.decodeAudioData(request.response, successCallback, errorCallback);

        function successCallback() {
            if (decodeCaseArray[index].result)
                testPassed("The " + decodeCaseArray[index].url +  " test: successCallback has been called correctly.");
            else
                testFailed("The " + decodeCaseArray[index].url + " test: successCallback was not called.");

            runDecodeTest(++index);
        }

        function errorCallback() {
            if (decodeCaseArray[index].result)
                testFailed("The " + decodeCaseArray[index].url + " test: errorCallback was called incorrectly.");
            else
                testPassed("The " + decodeCaseArray[index].url + " test: errorCallback has been called correctly.");

            runDecodeTest(++index);
        }
    }
    request.send();
}

setTimeout(() => {
    runDecodeTest(0);
}, 0);

</script>
</body>
</html>
