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

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

      destroy() {
        this.stopSizeObserver = true;
        super.destroy();
      }

      onArg(a_argName, a_value, a_editor, a_ignoreRedrawing, a_inner) {
        if (a_inner)
          return;
        if (a_argName == "value") {
          this.select("textarea")[0].value = a_value;
          return;
        }
        if (a_editor != this)
          this.update();
      }

      getActionDomElement() {
        return fcf.select(this.getDomElement(), "textarea")[0];
      }

      onInput(a_event){
        this.setArg("value", this.getActionDomElement().value);
      }

      onKeyPress(a_event){
        if (a_event.key == "Enter"){
          let element = this.getActionDomElement();
          let value = element.value;
          let end = element.selectionEnd;
          let pos = element.selectionStart;
          let ns = 0;
          for(let i = pos-1; i >= 0; --i){
            let char = value[i];
            let charcode = value.charCodeAt(i);
            if (char == "\r" || char == "\n")
              break;
            if (charcode>32)
              ns = 0;
            else
              ++ns;
          }
          a_event.preventDefault();
          a_event.stopPropagation();

          let fill = "\n";
          for(let i = 0; i < ns; ++i)
            fill += " ";
          let content = value.substring(0, pos) + fill + value.substring(end);
          this.getActionDomElement().value = content;
          element.selectionEnd = end + fill.length;
          element.selectionStart = pos + fill.length;
          this.onInput();
        }
      }

      sizeObserver(){
        let self = this;
        setTimeout(()=>{
          if (self.stopSizeObserver)
            return;
          let element = self.getActionDomElement();
          if (!element)
            return;
          let height = fcf.height(element);
          let heightStr = height+"px";
          if (!!height && self.getArg("height") != heightStr)
            self._setArg("height", heightStr);
          self.sizeObserver();
        },100);
      }

    };
  }
});
