if ('serviceWorker' in navigator) {
  //navigator.serviceWorker.register('/sw.js', {scope: './'}).then(function() {
      // Registration was successful. Now, check to see whether the Service Worker is controlling the page.
      if (navigator.serviceWorker.controller) {
        // If .controller is set, then this page is being actively controlled by the Service Worker.
        // Show the interface for sending messages to the service worker.
        showCommands();
      } else {
        // If .controller isn't set, then prompt the user to reload the page so that the Service Worker can take
        // control. Until that happens, the Service Worker's message handler won't be used.
        document.querySelector('#status').textContent =
          'Please reload this page to allow the service worker to take control.';
      }
  //}).catch(function(error) {
    // Something went wrong during registration. The service-worker.js file
    // might be unavailable or contain a syntax error.
    //document.querySelector('#status').textContent = error;
  //});
} else {
  // The current browser doesn't support Service Workers.
  var aElement = document.createElement('a');
  aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
  aElement.textContent = 'Service Workers are not supported in the current browser.';
  document.querySelector('#status').appendChild(aElement);
}

//jio = jIO.createJIO({type: "indexeddb", database: "cribjs"});

jio = jIO.createJIO({type:"dav", url: "https://cedriclendav.node.vifib.com/toto", basic_login: btoa("cedriclen:foo")})

function setStatus(statusMessage) {
  document.querySelector('#status').textContent = statusMessage;
}

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

function showCommands() {
  document.querySelector('#add').addEventListener('click', function() {
    var url = document.querySelector('#url').value;
    sendMessage({
      command: 'add',
      url: url,
      information: new Blob([document.querySelector('#information').value], {
        type: document.querySelector('#mimetype').value
      })
    }).then(function() {
      // If the promise resolves, just display a success message.
      setStatus('Added to cache:  ' + url + ' at ' + Date());
    }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
  });

  document.querySelector('#delete').addEventListener('click', function() {
    sendMessage({
      command: 'delete',
      url: document.querySelector('#url').value
    }).then(function() {
      // If the promise resolves, just display a success message.
      setStatus('Deleted from cache.');
    }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
  });

  document.querySelector('#list-contents').addEventListener('click', function() {
    sendMessage({
      command: 'keys'
    }).then(function(data) {
      var contentsElement = document.querySelector('#contents');
      // Clear out the existing items from the list.
      while (contentsElement.firstChild) {
        contentsElement.removeChild(contentsElement.firstChild);
      }

      // Add each cached URL to the list, one by one.
      data.urls.forEach(function(url) {
        var liElement = document.createElement('li'),
          aElement = document.createElement('a');
        aElement.setAttribute('href', url);
        aElement.textContent = url;
        liElement.innerHTML = aElement.outerHTML;
        contentsElement.appendChild(liElement);
      });
    }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
  });

  document.querySelector('#get').addEventListener('click', function() {
    console.log("bar");
    getContent(document.querySelector('#url').value,
      function() {
        document.querySelector('#mimetype').value = this.getResponseHeader("content-type");
        document.querySelector('#information').value = this.responseText;
      }
    );
  })

  document.querySelector('#save-path').value = document.location.origin;
  document.querySelector('#save-contents').addEventListener('click', function() {
    console.log('asking for the keys');
    var path_to_save, path_to_save_length, application_id;
    path_to_save = document.querySelector('#save-path').value
    application_id = document.querySelector('#save-id').value
    path_to_save_length = path_to_save.length
    sendMessage({
      command: 'keys'
    }).then(function(data) {
      // Add each cached URL to the list, one by one.
      console.log("foo");
      return new RSVP.Queue()
        .push(function() {
          console.log("put");
          return RSVP.all(
            [jio.put("/" + application_id + ".attachment/", {
           // url: path_to_save
              }),
             jio.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 = data.urls.length; i < i_len; i += 1) {
            url = new String(data.urls[i]);
            if (url.indexOf(path_to_save) === 0) {
              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)
            extension = getExtension(url)
            console.log("Pushing attachment " + url + " to " + path_to_save);
            promise_list.push(
              jio.putAttachment("/" + application_id + ".attachment/", btoa(url) + extension,
                response.target.response
              )
            );
          };
          return RSVP.all(promise_list)
        })
        .push(undefined, function(error) {
          console.log(error);
        });
    }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
  });

  document.querySelector('#load-path').value = document.location.origin;
  document.querySelector('#load-contents').addEventListener('click', function() {
    console.log('asking for the keys');
    var url_list = [],
      application_id;
    application_id = document.querySelector('#load-id').value
    return new RSVP.Queue()
      .push(function() {
        console.log("put");
        return jio.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.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
        console.log(url_list);
        console.log(response_list);
        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);
          sendMessage({
            command: 'add',
            url: document.querySelector('#load-path').value + url,
            information: response_list[i]
          })
        }
      })
      .push(undefined, function(error) {
        console.log(error);
      });
  });

  document.querySelector('#mass-remove').addEventListener('click', function() {
    var url_list = document.querySelector('#mass-remove-list').value.match(/[^\r\n]+/g),
      url_list_length = url_list.length,
      i;
    console.log(url_list)
    for (i = 0; i < url_list_length; i += 1) {
      console.log(url_list[i])
      sendMessage({
        command: 'delete',
        url: url_list[i],
      }).then(function() {
        // If the promise resolves, just display a success message.
        setStatus('Deleted from cache.');
      }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
    }
  });

  document.querySelector('#commands').style.display = 'block';
}

function sendMessage(message) {
  // This wraps the message posting/response in a promise, which will resolve if the response doesn't
  // contain an error, and reject with the error if it does. If you'd prefer, it's possible to call
  // controller.postMessage() and set up the onmessage handler independently of a promise, but this is
  // a convenient wrapper.
  return new Promise(function(resolve, reject) {
    var messageChannel = new MessageChannel();
    messageChannel.port1.onmessage = function(event) {
      if (event.data.error) {
        reject(event.data.error);
      } else {
        resolve(event.data);
      }
    };

    // This sends the message data as well as transferring messageChannel.port2 to the service worker.
    // The service worker can then use the transferred port to reply via postMessage(), which
    // will in turn trigger the onmessage handler on messageChannel.port1.
    // See https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage
    navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
  });
}

function getContent(url, reqListener) {
  var oReq = new XMLHttpRequest();
  oReq.onload = reqListener;
  oReq.open("get", url, true);
  oReq.send();
}