/*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("updateHeader", "updateHeader")
  .declareAcquiredMethod("getUrlParameter", "getUrlParameter")
  .declareAcquiredMethod("getSetting", "getSetting")
  .declareAcquiredMethod("getUrlFor", "getUrlFor")

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

  .onStateChange(function () {
  })

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

    return new RSVP.Queue()
      .push(function () {
        return RSVP.all([
          gadget.getUrlFor({command: 'history_previous'})
        ]);
      })
      .push(function (url_list) {
        return gadget.updateHeader({
          page_title: "Torrent index import"
          //selection_url: url_list[0]
        });
      });
  })

  .declareMethod("render", function (options) {
    var gadget = this;
    return RSVP.Queue()
      .push(function () {
        if (options.magnet_uri) {
          var redirect = "mynij_search";
          //automatically download the magnet
          return gadget.state.torrent_gadget.download(
            options.magnet_uri,
            redirect);
        }
      });
  });

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