import { bindable, bindingMode, computedFrom, customElement } from "aurelia-framework";
import { UIInternal } from "../../utils/ui-internal";

@customElement("ui-toggle")
export class UIToggle {
  @bindable({ defaultBindingMode: bindingMode.twoWay })
  public checked: AnyObject;
  @bindable()
  public model: AnyObject;

  @bindable()
  public matcher: () => void;
  @bindable()
  public disabled: boolean = false;

  @bindable()
  public labelOn: string = "";
  @bindable()
  public labelOff: string = "";
  @bindable()
  public width: string;
  @bindable()
  public labelPosition: "outside" | "inside" = "outside";

  @computedFrom('labelOn', 'labelOff', 'width', 'labelPosition')
  public get optionStyle() {
    let style = {};
    if (this.labelOn?.length > 0) {
      style["--toggle-on"] = `'${this.labelOn}'`;
    }
    if (this.labelOff?.length > 0) {
      style["--toggle-off"] = `'${this.labelOff}'`;
    }
    if (this.labelOff?.length > 0) {
      style["width"] = this.width;
    }
    if (this.labelPosition == "outside") {
      style["--toggle-on"] = "''";
      style["--toggle-off"] = "''";
    }

    return style;
  }
  labelOnChanged() {
    if (this.labelOn?.length == 0 && this.labelOff?.length == 0) {
      this.labelPosition = "inside";
    }
  }
  labelOffChanged() {
    if (this.labelOn?.length == 0 && this.labelOff?.length == 0) {
      this.labelPosition = "inside";
    }
  }
  protected isDisabled: boolean = false;

  constructor(protected element: Element) { }

  public disable(b: boolean): void {
    this.isDisabled = b;
  }

  protected bind(): void {
    if (isTrue(this.checked)) {
      this.checked = true;
    }
  }

  protected checkChanged($event: MouseEvent) {
    $event.preventDefault();
    $event.stopPropagation();
    if (!this.disabled) {
      this.checked = !this.checked;
    }
    this.element.dispatchEvent(UIInternal.createEvent("change", this));
  }
}
