import {
  Directive,
  EventEmitter,
  ElementRef,
  Input,
  HostListener,
  Output
} from '@angular/core'
import { FileUploader } from '../models/FileUploader.class'

@Directive({
  selector: '[appFileSelect]',
  standalone: false
})
export class FileSelectDirective {
  @Input() uploader?: FileUploader
  @Output() fileSelected: EventEmitter<File[]> = new EventEmitter<File[]>()

  protected element: ElementRef

  constructor(element: ElementRef) {
    this.element = element
  }

  /**
   * Checks if files exist in the input after input change
   */
  isEmptyAfterSelection(): boolean {
    return !!this.element.nativeElement.attributes.multiple
  }

  @HostListener('change')
  onChange(): void {
    const files = this.element.nativeElement.files

    this.uploader?.addToQueue(files)

    this.fileSelected.emit(files)
    if (this.isEmptyAfterSelection()) {
      this.element.nativeElement.value = ''
    }
  }
}
