<script src="../../../../resources/js-test.js"></script>
<script src="../../resources/shared.js"></script>
<script>

var child;

function waitForChildToBeClosed()
{
    if (child && !child.closed) {
        setTimeout(waitForChildToBeClosed, 0);
        return;
    }

    if (window.testRunner) {
        gc();
        finishTheTest();
    } else {
        debug("The original blob object we created will go away after garbage collection. Since we can't reliably cause synchronous GC in the browser, we'll wait 5 seconds before continuing the test.");
        setTimeout(finishTheTest, 5000);
    }
}

child = window.open("", "childWindow");
if (child) {
    child.close();
    setTimeout(waitForChildToBeClosed, 0);
}

var testGenerator;

function continueWithEvent(event)
{
    testGenerator.next(event);
}

function asyncContinue()
{
    setTimeout("testGenerator.next();", 0);
}

function idbRequest(request)
{
    request.onerror = continueWithEvent;
    request.onsuccess = continueWithEvent;
}

var db;

function finishTheTest()
{
    request = window.indexedDB.open("blob-cursor1.html");
    request.onsuccess = function(event) {
        db = event.target.result;
        testGenerator = testSteps();
        testGenerator.next();
    }
}

function* testSteps()
{
    debug("Now let's retrieve the blobs using a cursor.");

    var blobResults = [];
    objectStore = db.transaction("TestObjectStore").objectStore("TestObjectStore");
    objectStore.openCursor().onsuccess = function(event) {
        let cursor = event.target.result;
        if (cursor) {
            debug("Got item from cursor");
            blobResults.push(cursor.value);
            cursor.continue();
        }
        else {
            debug("Finished cursor");
            asyncContinue();
        }
    };

    event = yield;
    debug("blobResults.length is " + blobResults.length);
    
    imageForBlob = function(index, blob) {
        debug("  Result " + index + " is " + blob);

        const url = URL.createObjectURL(blob);

        img = document.createElement("img");
        img.onload = function(event) {
            debug("Image " + index + " loaded successfully");
            URL.revokeObjectURL(url);
            asyncContinue();
        }
        img.onerror = function(event) {
            debug("Image " + index + " failed to load");
            URL.revokeObjectURL(url);
            asyncContinue();
        }
        
        img.src = url;
        document.body.appendChild(img);        
    };
    
    for (blob in blobResults)
        imageForBlob(blob, blobResults[blob]);
    
    yield;
    yield;
    
    finishJSTest();
 }
 </script>