import { Component, Input, OnChanges } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { CircleButtonType, CircleButtonTypes, IqserDialog, Toaster } from '@iqser/common-ui';
import { TenantsService } from '@iqser/common-ui/lib/tenants';
import { Dossier, File, ProcessingFileStatuses } from '@red/domain';
import { PermissionsService } from '@services/permissions.service';
import { DownloadDialogComponent } from '@shared/dialogs/download-dialog/download-dialog.component';
import { FileDownloadService } from '@upload-download/services/file-download.service';

@Component({
    selector: 'redaction-file-download-btn',
    templateUrl: './file-download-btn.component.html',
})
export class FileDownloadBtnComponent implements OnChanges {
    @Input({ required: true }) files: File[];
    @Input({ required: true }) dossier: Dossier;
    @Input({ required: true }) buttonId: string;
    @Input() tooltipPosition: 'above' | 'below' | 'before' | 'after' = 'above';
    @Input() type: CircleButtonType = CircleButtonTypes.default;
    @Input() tooltipClass: string;
    @Input() disabled = false;

    tooltip: string;
    canDownloadFiles: boolean;
    invalidDownload = false;

    constructor(
        private readonly _permissionsService: PermissionsService,
        private readonly _tenantsService: TenantsService,
        private readonly _fileDownloadService: FileDownloadService,
        private readonly _dialog: IqserDialog,
        private readonly _toaster: Toaster,
    ) {}

    ngOnChanges(): void {
        this.invalidDownload = this.files.some(file => file.processingStatus === ProcessingFileStatuses.ERROR);
        this.canDownloadFiles = this._permissionsService.canDownloadFiles(this.files, this.dossier);
        this.tooltip = this.canDownloadFiles ? _('dossier-overview.download-file') : _('dossier-overview.download-file-disabled');
    }

    async downloadFiles() {
        const ref = this._dialog.openDefault(DownloadDialogComponent, {
            data: { dossier: this.dossier, files: this.files },
        });
        const result = await ref.result();
        if (!result) {
            return;
        }

        const downloadRequest = this._fileDownloadService.downloadFiles({
            dossierId: this.dossier.id,
            fileIds: this.files.map(f => f.id),
            ...result,
        });

        await downloadRequest
            .then(() =>
                this._toaster.info(_('download-status.queued'), {
                    params: { downloadHref: `/ui/${this._tenantsService.activeTenantId}/main/downloads` },
                }),
            )
            .catch(() => this._toaster.error(_('download-status.error')));
    }
}
