<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-svg-image1.html");
    request.onsuccess = function(event) {
        db = event.target.result;
        testGenerator = testSteps();
        testGenerator.next();
    }
}

function* testSteps()
{
    debug("Now let's retrieve the svg image blob.");

    objectStore = db.transaction("TestObjectStore").objectStore("TestObjectStore");
    idbRequest(objectStore.get("foo"));
    event = yield;
    
    var blob = event.target.result;

    debug("  Result is " + blob);

    const url = URL.createObjectURL(blob);

    img = document.createElement("img");
    img.onload = function(event) {
        debug("Image loaded successfully");
        URL.revokeObjectURL(url);
        asyncContinue();
    }
    img.onerror = function(event) {
        debug("Image failed to load");
        URL.revokeObjectURL(url);
        asyncContinue();
    }
    
    img.src = url;
    document.body.appendChild(img);        

    yield;
    
    finishJSTest();
 }
 </script>