import { bindable, BindingEngine, computedFrom, containerless, customElement,  signalBindings } from "aurelia-framework";
import { Language } from '../../model/common-model';
import { Config } from "../../config";
import { UITextarea } from './ui-textarea';
import { observable } from "aurelia-typed-observable-plugin";
import { MLInputHelper } from "./helpers/ml-input-helper";

@customElement("ui-ml-textarea")
@containerless
export class UIMLTextarea extends UITextarea {
  @bindable()
  public languages: AnyObject[];
  @observable
  public selectedLanguage: Language;
  @bindable()
  public selectedLanguageCode: string;
  private uITextArea: UITextarea;

  private mlInputHelper: MLInputHelper;

  constructor(element: Element, private config: Config, bindingEngine: BindingEngine) {
    super(element, bindingEngine);
    
    this.isValueObservable = false;
    this.mlInputHelper = new MLInputHelper(this);
    this.mlInputHelper.changeSelectedLangage();
  }

  protected onClear(): void {
    this.mlInputHelper.onClear();
  }

  public updateLanguageCode(code){
    this.selectedLanguageCode = code;
  }

  protected selectedLanguageCodeChanged(newValue, oldValue){
    this.mlInputHelper.selectedLanguageCodeChanged(newValue, oldValue);
  }

  protected bind() {
    this.uITextArea.allowClear = this.allowClear;
    this.uITextArea.isValueObservable = false;
    if(this.selectedLanguageCode != null){
      this.mlInputHelper.setSelectedLanguage();
    }
    let _this = this;
    this.mlInputHelper.rebindSubscribers(() => {
      setTimeout(() => {
        _this.textareaAutoResize();
      }, 50);
    });
    super.bind();
  }

  @computedFrom("value")
  get isTranslatable() {
    return this.mlInputHelper.isTranslatable();
  }

  protected detached() {
    this.mlInputHelper.disposeSubscribers();
    super.detached();
  }

  protected attached() {
    this.inputEl = this.uITextArea.inputEl as HTMLTextAreaElement;
    super.attached();
  }

  protected selectedLanguageChanged() {
    setTimeout(() => {
      this.textareaAutoResize();
    }, 50);
  }
}
