fcf.module({
  name: "fcfDBControls:templates/select.wrapper.js",
  dependencies: ["fcfControls:templates/view.wrapper.js"],
  module: function(Wrapper){
    return class BDSelectWrapper extends Wrapper{

      constructor(a_initializeOptions) {
        super(a_initializeOptions);
        this._menuActive = false;
      }

      attach(a_options) {
        let self = this;
        fcf.addDomListener(window, "click", this, () => { return self.onMenuClose(); });
        super.attach(a_options);
      }

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

      onInput(a_event) {
        let element     = this.getDomElement();
        let rect        = element.getBoundingClientRect();
        let menu        = this.getChild("menu");
        let menuWidth   = rect.right - rect.left;
        this._menuActive = true;
        menu.setArg("find", this.select("input")[0].value);
        menu.setArg("fcfStyle", "dislplay: block;" +
                                "width: " + menuWidth + "px;"
                                );
      }

      onClickInput(a_event) {
        a_event.stopPropagation();
      }

      onButtonClick(a_event) {
        a_event.stopPropagation();
        if (this._menuActive){
          this.onMenuClose()
          return;
        }
        let element       = this.getDomElement();
        let rect          = element.getBoundingClientRect();
        let menu          = this.getChild("menu");
        let menuWidth     = rect.right - rect.left;
        this._menuActive  = true;
        menu.setArg("find", "");
        menu.setArg("fcfStyle", "display: block;" +
                                "width: " + menuWidth + "px;" +
                                "z-index: " + fcf.getModalZIndex() + ";"
                                );
      }

      onMenuClose() {
        if (!this._menuActive)
          return;
        this._menuActive  = false;
        let menu          = this.getChild("menu");
        if (!menu)
          return;
        menu.setArg("fcfStyle", "display: none;");
        this.select("input")[0].value = this._getFriendlyValue();

      }

      onSelect(a_event, a_record) {
        a_event.stopPropagation();
        this.onMenuClose();
        this.setArg("value", a_record);
        this.emit("change", {value: a_record});
      }

      _getFriendlyValue() {
        let value = this.getArg("value");
        return typeof value == "object" && !fcf.empty(value["@title"]) ? value["@title"] : "";
      }

    };
  }
});
