import { ChangeDetectionStrategy, ChangeDetectorRef, Component, forwardRef, HostBinding, HostListener, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'ui-select-bullet',
  templateUrl: 'select-bullet.component.html',
  styleUrls: ['select-bullet.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => UiSelectBulletComponent),
      multi: true,
    },
  ],
})
export class UiSelectBulletComponent implements ControlValueAccessor {
  private selected: any;
  @Input() value: any = true;

  @HostBinding('class.disabled') @Input() disabled: boolean;

  get checked(): boolean {
    return this.selected == this.value;
  }

  private onChange = (v: any) => {};
  private onTouched = () => {};

  constructor(private cdr: ChangeDetectorRef) {}

  writeValue(obj: any): void {
    this.selectValue(obj, false);
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  registerOnChange(fn: any) {
    this.onChange = fn;
  }

  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  selectValue(value: any, emitEvent = true) {
    this.selected = value;

    if (emitEvent) {
      this.onChange(this.value);
      this.onTouched();
    }

    this.cdr.markForCheck();
  }

  @HostListener('click', ['$event'])
  select(event: MouseEvent) {
    event?.preventDefault();
    event?.stopPropagation();

    if (this.disabled) {
      return;
    }
    if (this.checked) {
      this.selected = undefined;
    } else {
      this.selected = this.value;
    }

    this.onChange(this.checked ? this.value : undefined);

    this.onTouched();
    this.cdr.markForCheck();
  }
}
