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

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

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

  @bindable onChange: (args: { checked?: boolean }) => void = () => { };

  protected isDisabled: boolean = false;

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

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

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

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