/*jslint nomen: true, indent: 2, maxerr: 3, maxlen: 80*/
/*global window, RSVP, rJS, document*/
(function (window, document, rJS, RSVP) {
  var gadget;
  rJS(window)
  .setState({
    torrent_gadget : null
  })

  .declareAcquiredMethod("redirect", "redirect")
  .declareAcquiredMethod("getUrlParameter", "getUrlParameter")
  .declareAcquiredMethod("getSetting", "getSetting")
  .declareAcquiredMethod("setSetting", "setSetting")
  .declareAcquiredMethod("notifySubmitted", "notifySubmitted")

  .ready(function () {
    var gadget = this;
    return this.getDeclaredGadget("model")
      .push(function (model) {
        return gadget.changeState({
          model_gadget: model
        });
      });
  })

  .onStateChange(function () {
  })

  .declareMethod("render", function (options) {
    var gadget = this;

    return new RSVP.Queue()
      .push(function () {
        return gadget.updateHeader({
          page_title: "JSON Source import"
        });
      });
  })

  .declareMethod("loadSource", function (url) {
    return new RSVP.Queue()
    .push(function () {
      return jIO.util.ajax({
        url : url
      });
    })
    .push(undefined, function (error) {
      console.log(error);
      return undefined;
    })
    .push(function (response) {
      var source_json;
      if (!response)
        return undefined;
      source_json = JSON.parse(response.target.responseText);
      return source_json;
    });
  })

  .declareMethod("render", function (options) {
    var gadget = this,
        doc,
        promise_list = [],
        i;

    return gadget.loadSource(options.url)
      .push(function (source_list) {
        if (!source_list) {
          return gadget.notifySubmitted({
            message: "Failed to download source file from specified url...",
            status: "error"
          })
          .push(function () {
            return gadget.redirect({command: 'display', options: {
              page : "ojs_local_controller"
            }});
          });
        } else {
          for (i = 0; i < source_list.length; i += 1) {
            doc  = {};
            doc.title = source_list[i].title;
            doc.links = source_list[i].links;
            doc.status = "not built";
            doc.description = source_list[i].description || "";
            promise_list.push(gadget.state.model_gadget.createIndexDoc(doc));
          }
          return new RSVP.Queue()
            .push(function () {
              return RSVP.all(promise_list);
            })
            .push(function (result) {
              var count = result.length;

              return gadget.getSetting("build_dict", {})
              .push(function (build_dict) {
                var i;

                for (i = 0; i < result.length; i += 1) {
                  build_dict[result[i]] = {
                    links: source_list[i].links,
                    index_name: source_list[i].title,
                    jio_key: result[i],
                    id: Date.now()
                  };
                }
                return gadget.setSetting("build_dict", build_dict);
              })
              .push(function () {
                return gadget.notifySubmitted({
                  message: count + " Source(s) correctly imported!\n" +
                    "Imported source(s) will now build!",
                  status: "success"
                });
              })
              .push(function () {
                var options = {page : "mynij_search"};
                return gadget.redirect({command: 'display', options: options});
              });
            });
        }
      });
  });

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