'use strict';

var Resource = require('../../Resource');
var b64 = require('../../b64');

var Url = window.URL || window.webkitURL;

// a middleware for transforming XHR loaded Blobs into more useful objects

module.exports = function () {
    return function (resource, next) {
        if (!resource.data) {
            next();

            return;
        }

        // if this was an XHR load of a blob
        if (resource.xhr && resource.xhrType === Resource.XHR_RESPONSE_TYPE.BLOB) {
            // if there is no blob support we probably got a binary string back
            if (!window.Blob || typeof resource.data === 'string') {
                var type = resource.xhr.getResponseHeader('content-type');

                // this is an image, convert the binary string into a data url
                if (type && type.indexOf('image') === 0) {
                    resource.data = new Image();
                    resource.data.src = 'data:' + type + ';base64,' + b64.encodeBinary(resource.xhr.responseText);

                    resource.isImage = true;

                    // wait until the image loads and then callback
                    resource.data.onload = function () {
                        resource.data.onload = null;

                        next();
                    };
                }
            }
            // if content type says this is an image, then we should transform the blob into an Image object
            else if (resource.data.type.indexOf('image') === 0) {
                var src = Url.createObjectURL(resource.data);

                resource.blob = resource.data;
                resource.data = new Image();
                resource.data.src = src;

                resource.isImage = true;

                // cleanup the no longer used blob after the image loads
                resource.data.onload = function () {
                    Url.revokeObjectURL(src);
                    resource.data.onload = null;

                    next();
                };
            }
        }
        else {
            next();
        }
    };
};

@@ -1282,32 +1282,112 @@
               %7D;
+%0A%0A                    // next will be called on load%0A                    return;
 %0A               
@@ -2086,16 +2086,17 @@
      %7D;%0A
+%0A
         
@@ -2091,33 +2091,67 @@
 %7D;%0A%0A            
-%7D
+    // next will be called on load.
 %0A        %7D%0A     
@@ -2143,26 +2143,24 @@
         
-%7D%0A
         
 else %7B%0A 
@@ -2155,14 +2155,15 @@
     
-else %7B
+return;
 %0A   
@@ -2163,39 +2163,33 @@
 rn;%0A            
-next();
+%7D
 %0A        %7D%0A    %7D
@@ -2178,23 +2178,40 @@
  %7D%0A        %7D
+%0A%0A        next();
 %0A    %7D;%0A%7D;%0A

fix #58; always call next()