fcf.module({
  name: "fcfDBControls:templates/select+menu.wrapper.js",
  dependencies: ["fcf:NClient/Wrapper.js"],
  module: function(Wrapper){
    return class WrapperEx extends Wrapper {

      constructor(a_initializeOptions){
        super(a_initializeOptions);
        this._process = 0;
      }

      attach() {
        let self = this;

        this._end       = false;
        this._offset    = 0;
        this._size      = 10;
        fcf.addDomListener(this.getActionDomElement(), "scroll", this, (a_event)=>{
          self.onScroll(a_event)
        });

        if (this.getDomElement().style.display == "none")
          return super.attach();

        this._updateRows();

        return super.attach();
      }

      onArg(a_argName, a_value, a_editor, a_isInnerCall, a_suffix) {
        this.update();
      }

      onScroll(a_event){
        let element = this.getDomElement();
        if ((element.clientHeight*2) + this.getDomElement().scrollTop > this.getDomElement().scrollHeight){
          this._updateRows();
        }
      }

      onSelectRow(a_event, a_record){
        this.getParent().onSelect(a_event, a_record);
      }


      _updateRows() {
        let self = this;

        if (this._end)
          return;
        if (this._process)
          return;
        ++this._process;

        this.send({
          projection: this.getArg("projection"), 
          fields:     this.getArg("fields"), 
          find:       this.getArg("find"), 
          offset:     this._offset, 
          size:       this._size
        })
        .then((a_fields) => {
          if (a_fields.length < self._size) {
            self._end = true;
          }
          self._offset += this._size;
          self._appendRecords(a_fields);
          if (self._process > 1){
            self._process = 0;
            self._updateRows();
          } else {
            self._process = 0;
          }
        })
      }

      _appendRecords(a_records) {
        let self = this;
        fcf.each(a_records, (a_key, a_record)=>{
          let item = document.createElement("div");
          item.classList.add("fcf-select-data-item");
          item.innerHTML = a_record["@title"];
          this.getDomElement().appendChild(item);
          fcf.addDomListener(item, "click", self, (a_event)=>{
            self.onSelectRow(a_event, a_record);
          })
        })
      }


    };
  }
});
