import { Component, Input, Output, EventEmitter, HostListener, forwardRef  } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'toggle-switch',
  templateUrl: './toggle-switch.component.html',
  styleUrls: ['./toggle-switch.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ToggleSwitchComponent),
      multi: true
    }
  ]
})
export class ToggleSwitchComponent implements ControlValueAccessor {

  @Input() checked = false;
  @Input() disabled = false;
  @Input() label = "";
  @Output() checkedChange = new EventEmitter<boolean>();

  toggle(): void{
    if(this.disabled)
    {
      return;
    }

    this.checked = !this.checked;
    this.checkedChange.emit(this.checked);

    this.onChange(this.checked);
    this.onTouched();
  }

  /** Поддержка клавиатуры (пробел / Enter) */
  @HostListener('keydown.space', ['$event'])
  @HostListener('keydown.enter', ['$event'])
  onKeydown(event: KeyboardEvent) {
    event.preventDefault();
    this.toggle();
  }

  writeValue(value: unknown): void {
    this.checked = !!value;
  }

  registerOnChange(fn: (v: unknown) => void): void {
    this.onChange = fn;
  }

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

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

  private onChange = (_: unknown) => {};

  private onTouched = () => {};

} 
