import { ChangeDetectorRef, Component, HostListener, Inject } from '@angular/core';
import { FileUploadService } from '../services/file-upload.service';
import { OverlayRef } from '@angular/cdk/overlay';
import { StatusOverlayService } from '../services/status-overlay.service';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { handleFileDrop } from '@utils/file-drop-utils';
import { FileUploadModel } from '@upload-download/model/file-upload.model';
import { DOSSIER_ID } from '../../../tokens';

@Component({
    templateUrl: './file-drop.component.html',
})
export class FileDropComponent {
    constructor(
        private readonly _dialogRef: OverlayRef,
        private readonly _fileUploadService: FileUploadService,
        private readonly _activeDossiersService: ActiveDossiersService,
        private readonly _changeDetectorRef: ChangeDetectorRef,
        private readonly _statusOverlayService: StatusOverlayService,
        @Inject(DOSSIER_ID) private readonly _dossierId: string,
    ) {}

    close() {
        setTimeout(() => {
            this._dialogRef.detach();
        }, 150);
    }

    @HostListener('document:keydown.escape', ['$event'])
    onKeydownHandler() {
        this.close();
    }

    @HostListener('drop', ['$event'])
    onDrop(event: DragEvent) {
        const dossier = this._activeDossiersService.find(this._dossierId);
        handleFileDrop(event, dossier, this.uploadFiles.bind(this));
    }

    @HostListener('dragover', ['$event'])
    onDragOver(event) {
        event.stopPropagation();
        event.preventDefault();
    }

    async uploadFiles(files: FileUploadModel[]) {
        const fileCount = await this._fileUploadService.uploadFiles(files, this._dossierId);
        if (fileCount) {
            this._statusOverlayService.openUploadStatusOverlay();
        }
        this._dialogRef.detach();
        this._changeDetectorRef.markForCheck();
    }
}
