import { OverlayRef } from '@angular/cdk/overlay';
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { FileUploadModel } from '../model/file-upload.model';
import { FileUploadService } from '../services/file-upload.service';

@Component({
    selector: 'redaction-upload-status-overlay',
    templateUrl: './upload-status-overlay.component.html',
    styleUrls: ['./upload-status-overlay.component.scss'],
})
export class UploadStatusOverlayComponent implements OnInit {
    collapsed = true;
    uploadStatusInterval: number;

    constructor(
        readonly uploadService: FileUploadService,
        private readonly _overlayRef: OverlayRef,
        private readonly _changeDetectorRef: ChangeDetectorRef,
    ) {}

    get uploadError() {
        return !!this.uploadService.files.filter(file => file.completed && file.error).length;
    }

    ngOnInit() {
        this.uploadStatusInterval = window.setInterval(() => {
            // keep only errors
            this.uploadService.filterFiles();
            if (this.uploadService.files.length === 0) {
                this.closeDialog();
            }
        }, 2500);
    }

    cancelItem(item: FileUploadModel) {
        this.uploadService.removeFile(item);
    }

    uploadItem(item: FileUploadModel) {
        this.uploadService.scheduleUpload(item);
        this._changeDetectorRef.detectChanges();
    }

    closeDialog() {
        if (this.uploadStatusInterval) {
            clearInterval(this.uploadStatusInterval);
            this.uploadStatusInterval = null;
        }
        this.uploadService.stopAllUploads();
        this._overlayRef.detach();
    }
}
