import {
  Directive,
  HostBinding,
  Output,
  EventEmitter,
  HostListener
} from '@angular/core'

@Directive({
  selector: '[appDragNdrop]',
  standalone: false
})
export class DragNdropDirective {
  @HostBinding('class.fileover') fileOver: boolean = false
  @Output() fileDropped = new EventEmitter<any>()
  @Output() fileDraggedOver = new EventEmitter<any>()

  /**
   * Dragover listener
   */
  @HostListener('dragover', ['$event'])
  onDragOver(event: any) {
    event.preventDefault()
    event.stopPropagation()

    if (this.containsFiles(event) && !this.fileOver) {
      this.fileOver = true
      this.fileDraggedOver.emit()
    }
  }

  /**
   * Dragleave listener
   */
  @HostListener('dragleave', ['$event'])
  public onDragLeave(event: any) {
    event.preventDefault()
    event.stopPropagation()
    this.fileOver = false
  }

  /**
   * Drop listener
   */
  @HostListener('drop', ['$event'])
  public ondrop(event: any) {
    event.preventDefault()
    event.stopPropagation()
    this.fileOver = false

    const files = event.dataTransfer.files

    if (files.length > 0) {
      this.fileDropped.emit(files)
    }
  }

  /**
   * Checks wether dragging element contain files
   */
  private containsFiles(event: any) {
    if (event && event.dataTransfer && event.dataTransfer.types) {
      for (let i = 0; i < event.dataTransfer.types.length; i++) {
        if (event.dataTransfer.types[i] == 'Files') {
          return true
        }
      }
    }
  }
}
