/*global window, rJS, RSVP */
/*jslint indent: 2, maxerr: 3 */
(function(window, rJS, RSVP, jIO) {
    "use strict";

  function getStorageGadget(gadget) {
    var storage_gadget;
    return gadget.getDeclaredGadget("storage")
      .push(undefined, function () {
        return gadget.declareGadget(
          gadget.props.storage_gadget_url,
          {
            "scope": "storage",
            "sandbox": "iframe",
            "element": gadget.props.element.querySelector('div')
          }
        );
       })
  }
  
  rJS(window)
    .ready(function (g) {
      g.props = {};
      return g.getElement()
        .push(function (element) {
          g.props.element = element;
          g.props.storage_gadget_url = "https://cribjs.nexedi.net/gadget/crib-sw-storage-gadget.html";
         });
    })  
    .ready(function(gadget) {
      // Initialize the gadget local parameters
      gadget.state_parameter_dict = {};
      return getStorageGadget(gadget);
    })
    
    .declareMethod('allDocs', function(params) {
      return getStorageGadget(this)
      	.push(function (storage_gadget) {
          return storage_gadget.allDocs(params)
        });
    })
    
    .declareMethod('get', function(url) {
      return getStorageGadget(this)
      	.push(function (storage_gadget) {
          return storage_gadget.get(url)
        })
        .push(function (result) {
          return jIO.util.dataURItoBlob(result);
        });
    })
    
    .declareMethod('put', function(url, parameter) {
      var blob, gadget = this;
      if (parameter.blob !== undefined) {
        blob = parameter.blob;
      } else {
        blob = new Blob(
          [parameter.content], 
          {type: parameter.type,}
        );
      }
      return RSVP.Queue()
        .push(function () {
          return RSVP.all([
            getStorageGadget(gadget),
            jIO.util.readBlobAsDataURL(blob)
      	  ]);
        })
      	.push(function (result_list) {
          return result_list[0].put(url, result_list[1].target.result);
        })
        .push(console.log, console.log)
        ;
    })
    
    .declareMethod('remove', function(url) {
      return getStorageGadget(this)
      	.push(function (storage_gadget) {
          return storage_gadget.remove(url)
        });
    });

}(window, rJS, RSVP, jIO));