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

@customElement("ui-ml-input")
@containerless
export class UIMLInput extends UIInput {
  @bindable()
  public languages: AnyObject[];
  public selectedLanguage: Language;
  @bindable()
  public selectedLanguageCode: string;
  private inputElement: UIInput;

  private mlInputHelper: MLInputHelper;

  constructor(element: Element, config: Config, bindingEngine: BindingEngine) {
    super(element, config, bindingEngine);
    this.config = config;
    let _this = this;
    this.mlInputHelper = new MLInputHelper(this, () => _this.valueChanged());
    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() {
    super.bind();
    this.inputElement.allowClear = this.allowClear;
    if(this.selectedLanguageCode != null){
      this.mlInputHelper.setSelectedLanguage();
    }
    this.valueChanged();
  }

  protected valueChanged() {
    this.mlInputHelper.rebindSubscribers();
  }

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