import { Component, ElementRef, Inject, ViewChild } from '@angular/core';
import { BaseDialogComponent } from '@iqser/common-ui';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { firstValueFrom } from 'rxjs';
import { RedactionImportService } from '@services/files/redaction-import.service';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { HttpStatusCode } from '@angular/common/http';
import { extractPageRanges } from '@utils/page-ranges-mapper';
import { File } from '@red/domain';

interface ImportData {
    dossierId: string;
    fileId: string;
}

@Component({
    templateUrl: './import-redactions-dialog.html',
    styleUrls: ['./import-redactions-dialog.scss'],
})
export class ImportRedactionsDialogComponent extends BaseDialogComponent {
    @ViewChild('attachFileInput', { static: true }) attachFileInput: ElementRef;

    fileToImport: Blob | null;
    numberOfPages = 0;
    onlyForSpecificPages = false;
    rangesValue = '';

    constructor(
        protected readonly _dialogRef: MatDialogRef<ImportRedactionsDialogComponent>,
        private readonly _redactionImportService: RedactionImportService,
        @Inject(MAT_DIALOG_DATA) readonly data: ImportData,
    ) {
        super(_dialogRef);
    }

    get disabled(): boolean {
        if (!this.fileToImport) {
            return true;
        }
        if (this.onlyForSpecificPages) {
            try {
                extractPageRanges(this.rangesValue, { numberOfPages: this.numberOfPages } as File);
            } catch (e) {
                return true;
            }
        }
        return false;
    }

    get #pagesToImport(): Set<number> {
        const pageRanges = extractPageRanges(this.rangesValue, { numberOfPages: this.numberOfPages } as File);
        const pagesToImport = new Set<number>();
        pageRanges.forEach(r => {
            for (let i = r.startPage; i <= r.endPage; i++) {
                pagesToImport.add(i);
            }
        });

        return pagesToImport;
    }

    fileChanged(file: Blob | null) {
        this.fileToImport = file;
        if (!this.fileToImport) {
            this.onlyForSpecificPages = false;
            this.rangesValue = '';
            return;
        }
        this.#extractNumberOfPages(this.fileToImport);
    }

    async save(): Promise<void> {
        this._loadingService.start();

        const pagesToImport = this.onlyForSpecificPages ? this.#pagesToImport : null;
        const import$ = this._redactionImportService.importRedactions(
            this.data.dossierId,
            this.data.fileId,
            this.fileToImport,
            pagesToImport,
        );
        const result: any = await firstValueFrom(import$).catch(error =>
            this._toaster.error(_('import-redactions-dialog.http.error'), { error }),
        );
        this._loadingService.stop();

        if (result.status === HttpStatusCode.Ok) {
            this._toaster.success(_('import-redactions-dialog.http.success'));
            this.close();
        }
    }

    #extractNumberOfPages(file: Blob) {
        const reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onloadend = () => {
            this.numberOfPages = (reader.result as any).match(/\/Type[\s]*\/Page[^s]/g).length;
        };
    }
}
