import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import {
    ConfirmationDialogComponent,
    DialogConfig,
    DialogService,
    IConfirmationDialogData,
    LoadingService,
    TitleColors,
} from '@iqser/common-ui';
import { AddEditJustificationDialogComponent } from './add-edit-justification-dialog/add-edit-justification-dialog.component';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';
import { JustificationsService } from '@services/entity-services/justifications.service';
import { Justification } from '@red/domain';
import { firstValueFrom } from 'rxjs';

type DialogType = 'confirm' | 'addEditJustification';

@Injectable()
export class JustificationsDialogService extends DialogService<DialogType> {
    protected readonly _config: DialogConfig<DialogType> = {
        confirm: {
            component: ConfirmationDialogComponent,
        },
        addEditJustification: {
            component: AddEditJustificationDialogComponent,
            dialogConfig: { autoFocus: true },
        },
    };

    constructor(
        protected readonly _dialog: MatDialog,
        private readonly _loadingService: LoadingService,
        private readonly _dossierTemplatesService: DossierTemplatesService,
        private readonly _justificationService: JustificationsService,
    ) {
        super(_dialog);
    }

    confirmDelete(justifications: Justification[], dossierTemplateId: string) {
        const data: IConfirmationDialogData = {
            title: _('confirmation-dialog.delete-justification.title'),
            titleColor: TitleColors.WARN,
            question: _('confirmation-dialog.delete-justification.question'),
            translateParams: {
                count: justifications.length,
                justificationName: justifications[0].name,
            },
        };

        this.openDialog('confirm', data, async () => {
            this._loadingService.start();
            const justificationIds = justifications.map(j => j.id);
            await firstValueFrom(this._justificationService.delete(justificationIds, dossierTemplateId));
            await firstValueFrom(this._justificationService.loadAll(dossierTemplateId));
            this._loadingService.stop();
        });
    }
}
