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

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

  @bindable({ defaultBindingMode: bindingMode.oneTime })
  public name: string = "optGroup";

  @bindable()
  public disabled: boolean = false;

  protected isDisabled: boolean = false;

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

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

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

  protected onInputClicked($event: Event) {
    $event.stopPropagation();
    if (!this.disabled) {
      this.taskQueue.queueMicroTask(() => this.onChange({ checked: this.model }));
    }
    UIInternal.nextTick(() => this.element.dispatchEvent(UIInternal.createEvent("change", this)));
    return !this.disabled;
  }

  protected onLabelClicked($event: Event) {
    if (this.disabled) {
      return;
    }
    this.checked = this.model;
    this.onInputClicked($event);
  }
}