import { Directive, ElementRef, HostListener, inject, Input, OnInit } from '@angular/core';
import { AudioService } from '../services/audio.service';
import { AbstractControl } from '@angular/forms';

@Directive({
  selector: '[appDragSound]',
  standalone: true,
})
export class DragSoundDirective implements OnInit {
  private audioService = inject(AudioService);
  private elementRef = inject(ElementRef);
  private lastValue: number | null = null;

  @Input('appDragSound') formControl: AbstractControl | null = null;

  ngOnInit() {
    if (this.formControl) {
      this.lastValue = this.formControl.value;

      this.formControl.valueChanges.subscribe((newValue) => {
        if (this.lastValue !== newValue) {
          this.playSound();
          this.lastValue = newValue;
        }
      });
    }
  }

  private playSound() {
    this.audioService.playDragStepSound();
  }

  @HostListener('input')
  onInput() {
    if (!this.formControl) {
      this.playSound();
    }
  }
}
