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

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

  function loadContentFromZIPURL(gadget, zip_url) {
    var path_to_load, path_to_load_length, file_list, crib_sw_gadget,
      jio_gadget, url_list = [], url_number = 0;
    path_to_load = "";
    return new RSVP.Queue()
    .push(function () {
      return gadget.getDeclaredGadget('crib_sw_gadget');
    })
    .push(function (returned_gadget) {
      crib_sw_gadget = returned_gadget;
      return fetch(zip_url)
        .then(function (response) {                       // 2) filter on 200 OK
            if (response.status === 200 || response.status === 0) {
                return Promise.resolve(response.blob());
            } else {
                return Promise.reject(new Error(response.statusText));
            }
        });
    })
    .push(JSZip.loadAsync)
    .push(function (zip) {
      var promise_list = [];
      zip.forEach(function (relativePath, zipEntry) {
        var end_url;
        url_number += 1;
        if ( zipEntry.dir ) {
          return
        }
        if (!relativePath.startsWith("/") && !path_to_load.endsWith("/")) {
          end_url = path_to_load + "/" + relativePath 
        } else if (relativePath.startsWith("/") && path_to_load.endsWith("/")) {
          end_url = path_to_load + relativePath.substring(1);
        } else {
          end_url = path_to_load + relativePath 
        }
        promise_list.push(
          new RSVP.Queue().
            push(function () {
              return zipEntry.async('blob');
            })
            .push(function (result) {
              if ( end_url.endsWith(".js") ) {
                // This is a ugly hack as mimetype needs to be correct for JS
                result = result.slice(0, result.size, "application/javascript")
              } else if ( end_url.endsWith(".html") ) {
                // This is a ugly hack as mimetype needs to be correct for JS
                result = result.slice(0, result.size, "text/html")
              } else if ( end_url.endsWith(".css") ) {
                // This is a ugly hack as mimetype needs to be correct for JS
                result = result.slice(0, result.size, "text/css")
              } 
              return crib_sw_gadget.put(end_url, {blob: result})
            })
        )
      })
      return RSVP.all(promise_list)
    })
    .push(function() {
      gadget.props.element.querySelector(".crib-load-from-zip-status").textContent = "Loaded " + url_number + " files at "+ Date ()
    })
    .push(console.log, console.log)
  }

  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 loadContentFromZIPURL(gadget, jio_config);
    })
    .push(console.log, console.log)
  })

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