import { Directive, ElementRef, EventEmitter, HostBinding, HostListener, Input, Output, ViewChild } from '@angular/core';

@Directive({
  standalone: true,
  selector: '[henselDnD]'
})


export class HenselDnDDirective {

  private _disabled: boolean = false;
  public get disabled(): boolean {
    return this._disabled;
  }
  @Input()
  public set disabled(value: boolean) {
    this._disabled = value;
  }

  // tslint:disable-next-line: no-output-on-prefix
  @Output() onFileDropped = new EventEmitter<any>();
  @HostBinding('style.background-color') private backgroundColor;
  @HostBinding('style.opacity') private opacity;
  // @ViewChild('dndicon') icon: ElementRef;
  private icon: any;
  private _dragover: boolean = false;
  public get dragover(): boolean {
    return this._dragover;
  }
  public set dragover(value: boolean) {
    if (this._dragover === value) return;
    if (value && this.disabled) return;
    this._dragover = value;
    if (value) {
      if (!this.icon) {
        this.icon = document.getElementById('dndicon');
        if (this.icon) {
          this.lastIcon = this.icon.innerText;
          if (this.icon) this.icon.innerText = 'vertical_align_top';
        }
      }
      this.backgroundColor = '#76a9cb';
      this.opacity = '1';
    } else {
      setTimeout(() => {
        if (!this.dragover) {
          if (this.icon) this.icon.innerText = this.lastIcon;
          this.icon = null;
          delete this.opacity;
          delete this.backgroundColor;
        }
      }, 100);
    }
  }

  private lastIcon: string;


  //Dragover listener
  @HostListener('dragover', ['$event']) onDragOver(evt) {
    if (this.disabled) evt.dataTransfer.dropEffect = 'none';
    else evt.dataTransfer.dropEffect = 'copy';
    evt.preventDefault();
    evt.stopPropagation();
    this.dragover = true;
  }

  //Dragleave listener
  @HostListener('dragleave', ['$event']) public onDragLeave(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    this.dragover = false;
  }

  //Drop listener
  @HostListener('drop', ['$event']) public ondrop(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    if (!this._disabled) {
      const files = evt.dataTransfer.files;
      if (files.length > 0) this.onFileDropped.emit(files);
    }

    this.dragover = false;
  }


}
