import {
  Directive,
  ElementRef,
  HostListener,
  inject,
  input
} from '@angular/core';

import { shouldSelectOnFocus } from './form-field-focus.rules';

/**
 * Selects the full field value when the user focuses a text input or textarea.
 */
@Directive({
  selector: 'input[appSelectOnFocus], textarea[appSelectOnFocus]',
  standalone: true
})
export class SelectOnFocusDirective {
  readonly skipPassword = input(true);

  private readonly hostRef = inject<ElementRef<HTMLInputElement | HTMLTextAreaElement>>(ElementRef);

  @HostListener('focus')
  onFocus(): void {
    const element = this.hostRef.nativeElement;

    if (!shouldSelectOnFocus({
      type: element.type,
      value: element.value
    }, this.skipPassword())) {
      return;
    }

    element.select();
  }
}
