import { TaskQueue, bindable, computedFrom, customElement, inlineView, observable } from "aurelia-framework";

@customElement("ui-field-wrapper")
@inlineView(`<template class="ui-field__wrapper \${classes}">
  <slot></slot>
  </template>`)
export class UIFieldWrapper {
  @bindable()
  public plain: string | boolean = false;
  @observable
  private isEmpty = false;
  @observable
  private hasError = false;
  @observable
  private hasDisabled = false;
  @observable
  private hasReadonly = false;

  constructor(private element: Element, private taskQueue: TaskQueue) {
  }

  protected attached() {
    this.taskQueue.queueMicroTask(() => {
      const el: HTMLInputElement = this.element.querySelector("input, textarea, select, ui-input, ui-select, ui-date-picker, ui-ml-input, ui-ml-textarea");
      if (el != null) {
        if (el.tagName.toLowerCase() == 'select') {
          if (el.textContent?.trim()?.length == 0 && el.parentElement?.classList.contains('ui-input--readonly')) {
            this.isEmpty = true;
          }
        } else {
          const val = el.value;
          if (val?.length == 0 && el.parentElement?.classList.contains('ui-input--readonly')) {
            this.isEmpty = true;
          }
        }
        this.hasReadonly = el.hasAttribute('readonly');
        this.hasDisabled = el.hasAttribute('disabled');
        el.addEventListener("input-invalid", () => {
          this.hasError = true;
        });
        el.addEventListener("input-valid", () => {
          this.hasError = false;
        });
        el.addEventListener("input-readonly", () => {
          this.hasReadonly = true;
        });
        el.addEventListener("input-not-readonly", () => {
          this.hasReadonly = false;
        });
        el.addEventListener("input-disabled", () => {
          this.hasDisabled = true;
        });
        el.addEventListener("input-not-disabled", () => {
          this.hasDisabled = false;
        });
      }
    });
  }

  @computedFrom("plain", "isEmpty", 'hasError', 'hasDisabled', 'hasReadonly')
  get classes(): string {
    const classes = [];
    if (this.plain === "" || this.plain === "plain" || isTrue(this.plain)) {
      classes.push("ui-field__wrapper--plain");
    }
    if (this.isEmpty === true) {
      classes.push("ui-field__wrapper--empty");
    }
    if (this.hasDisabled) {
      classes.push("ui-field__wrapper--disabled");
    }
    if (this.hasError) {
      classes.push("ui-field__wrapper--invalid");
    }
    if (this.hasReadonly) {
      classes.push("ui-field__wrapper--readonly");
    }
    return classes.join(" ");
  }
}