/*globals window, document, RSVP, rJS,
         location, console*/
/*jslint indent: 2, maxlen: 80*/
(function (window, document, RSVP, rJS, location, console) {
  "use strict";

  function getExtension(url) {
    var extension = url.split('.').pop();
    if (extension.endsWith('/')) {
      return ".html";
    }
    return "." + extension;
  }

  rJS(window)
    .ready(function (g) {
    g.props = {};
  })
    .declareMethod('load', function (options) {
    var path_to_load, path_to_load_length, application_id, crib_sw_gadget, jio_config,
        jio_gadget, url_list = [], gadget = this;
    path_to_load = options.path;
    application_id = options.application_id;
    jio_config = options.jio_config;
    path_to_load_length = path_to_load.length;
    return new RSVP.Queue()
      .push(function () {
      return RSVP.all([
        gadget.getDeclaredGadget('crib_sw_gadget'),
        gadget.getDeclaredGadget('jio_gadget')]);
    })
      .push(function (gadget_list) {
      crib_sw_gadget = gadget_list[0];
      jio_gadget = gadget_list[1];
      return jio_gadget.createJio(jio_config);
    })
      .push(function () {
      return jio_gadget.allAttachments("/" + application_id + ".attachment/");
    })
      .push(function(response) {
      var promise_list = [],
          key, extension;
      for (key in response) {
        if (response.hasOwnProperty(key)) {
          extension = getExtension(key);
          console.log(key);
          url_list.push(atob(key.substr(0, key.length - extension.length)))
          promise_list.push(jio_gadget.getAttachment("/" + application_id + ".attachment/", key));
        }
      };
      return RSVP.all(promise_list)
    })
      .push(function(response_list) {
      var promise_list = [],
          i, i_len, url, index, response, location, location_len;
      location = document.location.origin;
      location_len = location.length
      for (i = 0, i_len = response_list.length; i < i_len; i += 1) {
        url = url_list[i]
        index = url.indexOf(location);
        if (index != -1)
          url = url.substr(index + location_len);
        console.log(path_to_load + url);
        promise_list.push( 
          crib_sw_gadget.put(path_to_load + url, {blob: response_list[i]})
        )
      }
      return RSVP.all(promise_list);
    })
      .push(function() {
      return url_list
    });
  })
    .declareMethod('save', function (options) {
    var path_to_save, path_to_save_length, application_id, crib_sw_gadget, jio_config,
        jio_gadget, url_list = [], saved_url_list = [], gadget = this;
    path_to_save = options.path;
    application_id = options.application_id;
    jio_config = options.jio_config;
    path_to_save_length = path_to_save.length;
    return new RSVP.Queue()
      .push(function () {
      return RSVP.all([
        gadget.getDeclaredGadget('crib_sw_gadget'),
        gadget.getDeclaredGadget('jio_gadget')]);
    })
      .push(function (gadget_list) {
      crib_sw_gadget = gadget_list[0];
      jio_gadget = gadget_list[1];
      return jio_gadget.createJio(jio_config);
    })
      .push(function (){
      return crib_sw_gadget.allDocs();
    })
      .push(function(data) {
      url_list = data.urls;
      // This is buggy, it fails if the document already exists with dav storage
      // XX Should be able to add some metadata here such as url, contributor, version ...
      return RSVP.all(
        [jio_gadget.put("/" + application_id + ".attachment/", {
        }),
         jio_gadget.putAttachment("/", application_id, new Blob([JSON.stringify({url: path_to_save})],{type: "application/json"}))  
        ]);      
    })
      .push(function() {
      var promise_list = [],
          i, i_len, url;
      for (i = 0, i_len = url_list.length; i < i_len; i += 1) {
        url = new String(url_list[i]);
        if (url.indexOf(path_to_save) === 0) {
          saved_url_list.push({url: url});
          promise_list.push(jIO.util.ajax({
            url: url,
            dataType: "blob"
          }));
        };
      };
      return RSVP.all(promise_list);
    })
      .push(function(response_list) {
      var promise_list = [],
          i, i_len, url, response, extension;
      for (i = 0, i_len = response_list.length; i < i_len; i += 1) {
        response = response_list[i];
        url = response.target.responseURL.substr(path_to_save_length);
        // This is tricky here, we use the extension for file storages in order to get the correct blob
        // It should be fixed
        saved_url_list[i].target = url;
        extension = getExtension(url);
        saved_url_list[i].target = extension;
        console.log("Will push attachment " + saved_url_list[i].url + " to " + url);
        promise_list.push(
          jio_gadget.putAttachment("/" + application_id + ".attachment/", btoa(url) + extension,
                                   response.target.response
                                  )
        );
      };
      return RSVP.all(promise_list);
    })
      .push(function() {
      return saved_url_list;
    })
      .fail(function(error) {
      gadget.props.element.querySelector(".crib-save-to-jio-status").textContent = error;
      console.log(error);
    });
  })

}(window, document, RSVP, rJS, location, console));