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

  .declareAcquiredMethod("updateHeader", "updateHeader")
  .declareAcquiredMethod("getUrlParameter", "getUrlParameter")
  .declareAcquiredMethod("getUrlFor", "getUrlFor")
  .declareAcquiredMethod("redirect", "redirect")
  .declareAcquiredMethod("getSetting", "getSetting")

  .ready(function () {
    var model_gadget,
    result_gadget,
    gadget = this;

    return gadget.getDeclaredGadget("model")
    .push(function (model) {
      model_gadget = model;
    })
    .push(function () {
      return gadget.getDeclaredGadget("result");
    })
    .push(function (result) {
      return gadget.changeState({
        model_gadget : model_gadget,
        result_gadget : result
      });
    });
  })

  .onStateChange(function () {
  })

  .declareMethod("render", function (options) {
    var gadget = this,
        index_list,
        drop_list = gadget.element.querySelector("#select_index");

    return new RSVP.Queue()
      .push(function () {
        return RSVP.all([
          gadget.getUrlFor({command: 'history_previous'})
        ]);
      })
      .push(function (url_list) {
        return gadget.updateHeader({
          page_title: "Mynij Search"
          //selection_url: url_list[0]
        });
      })
      .push(function () {
        //return gadget.state.model_gadget.get_available_indices();
        return gadget.getSetting('index_list', []);
      })
      .push(function (results) {
        index_list = results;

        while (drop_list.firstChild) {
          drop_list.removeChild(drop_list.firstChild);
        }
        results.forEach((item, i) => {
            var option_item = document.createElement("option");
            option_item.value = item;
            option_item.appendChild(document.createTextNode(item));
            drop_list.appendChild(option_item);
        });

      })
      .push(function () {
        var limit = options.limit | 100,
            index = options.index;
        if (options.q) {
          if (index_list.indexOf(index) === -1)
            index = undefined;
          else
            drop_list.value = index;
          gadget.element.querySelector("#search_input").value = options.q;
          return gadget.defer_search(options.q, index, limit);
        } else {
          return gadget.clear();
        }
      });
  })

  .declareJob("clear", function () {
    var gadget = this;
    this.element.querySelector("#search_input").value = "";
    return this.state.result_gadget.clear()
      .push(function () {
        document.getElementById("logo-search").classList.remove('hide');
        return gadget.state.result_gadget.hideResultBox();
      });
  })

  .declareJob("defer_search", function (search_text, index, limit) {
    var gadget = this,
        top = document.getElementById("logo-search");

    if(top) {
      top.classList.add("hide");
    }
    return gadget.state.result_gadget.startLoading()
      .push(function () {
        return gadget.state.result_gadget.showResultBox();
      })
      .push(function () {
        return gadget.search(search_text, limit, index)
      })
      .push(function () {
        return gadget.add_searx_results(search_text);
      });
  })
  .declareMethod("search", function (key, limit, index) {
    var gadget = this,
        chosen_index;
    if (index) {
      chosen_index = index;
    } else {
      chosen_index = document.getElementById("select_index").value;
    }
    if (chosen_index === null) {
      return gadget.state.result_gadget.addItem(
        {
          title: "Error : No index built",
          link: "",
          body: ""
        },
        key);
    }
    return gadget.state.result_gadget.clear()
      .push(function () {
        console.log("starting search");
        return gadget.state.model_gadget.search(key, chosen_index, limit);
      })
      .push(function (result) {
        var result_queue = new RSVP.Queue(),
            i;
        console.log("search done");
        function push_result(result) {
          result_queue
            .push(function () {
              return gadget.state.model_gadget.get_page(result);
            })
            .push(function (page) {
              return gadget.state.result_gadget.addItem(page, key);
            })
            .push(undefined, function (error) {
              console.log("Error while getting result: " + error);
            });
        }
        if (!result || result.length === 0) {
          return gadget.state.result_gadget.addItem(
            {
              title : "No results found",
              link : ""
            },
            "");
        } else {
          for (i = 0; i < result.length; i += 1) {
            push_result(result[i]);
          }
          return result_queue;
        }
      });
  })

  .declareMethod("add_searx_results", function (key) {
    var gadget = this;

    return new RSVP.Queue()
      .push(function () {
        return jIO.util.ajax({
          url : "https://cors-anywhere.herokuapp.com/search.disroot.org/?q=" +
            key + "&category_general=on&theme=oscar"
        });
      })
      .push(undefined, function () {
        return undefined;
      })
      .push(function (resultHTML) {
        var i,
          promise_list = [],
          elements,
          doc;

        if (!resultHTML) {
          return gadget.state.result_gadget.add_searx_no_result(
            "An error occured while getting result, please try again!"
          );
        }
        doc = new DOMParser().parseFromString(
          resultHTML.currentTarget.response,
          "text/html");
        elements = doc.body.querySelectorAll('div.result.result-default');
        if (elements.length === 0)
          return gadget.state.result_gadget.add_searx_no_result(
            "No result from your input, please update and try again."
          );
        for (i = 0; i < elements.length; i += 1) {
          promise_list.push(gadget.state.result_gadget.show_searx_result(
            elements[i],
            key));
        }
        return RSVP.all(promise_list);
      });
  })

  .onEvent("submit", function (event) {
    var gadget = this,
        search_key = document.getElementById("search_input").value,
        index = document.getElementById("select_index").value;
    return gadget.redirect({"command": "display", "options": {
      page: "mynij_search",
      q: search_key,
      index: index
    }});
  });
}(window, document, rJS, RSVP));