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

  function massRemoveFromCache(gadget, event) {
    var url_list = gadget.props.element.querySelector("form.crib-mass-remove textarea").value.match(/[^\r\n]+/g),
      url_list_length = url_list.length;
    return new RSVP.Queue()
    .push(function () {
      var i,
        promise_list = [];
      for (i = 0; i < url_list_length; i += 1) {
        promise_list.push(gadget.crib_sw_remove(url_list[i]));
      };
      return RSVP.all(promise_list);
    })
    .push(function() {
      gadget.props.element.querySelector(".crib-mass-remove-status").textContent = "Removed " + url_list.length + " files at "+ Date ()
    })
    .fail(function(error) {
      gadget.props.element.querySelector(".crib-mass-remove-status").textContent = error;
      console.log(error);
    });
  }  
  
  rJS(window)
    .ready(function (g) {
      g.props = {};
      return g.getElement()
        .push(function (element) {
          g.props.element = element;
          g.props.start_deferred = RSVP.defer();
         });
    })
    .declareAcquiredMethod("crib_sw_remove", "crib_sw_remove")
    .declareMethod('render', function (options) {
      var gadget = this;
      if (options === undefined)
        options = {};
      gadget.props.options = options;
      return new RSVP.Queue()
        .push(function () {
          return gadget.props.start_deferred.resolve();
        })  
    })
    .declareService(function () {
      var gadget = this;
      return new RSVP.Queue()
        .push(function () {
          return gadget.props.start_deferred.promise;
        })
        .push(function () {
          var promise_list = [];
          // promise to remove content from cache
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".crib-mass-remove"),
            'submit',
            false,
            function (event) {massRemoveFromCache(gadget, event)}
          ));
          return RSVP.all(promise_list);
        });
    })  
}(window, rJS, loopEventListener));