import { Component, Inject } from '@angular/core';
import { BaseDialogComponent } from '@iqser/common-ui';
import { Validators } from '@angular/forms';
import { IDossierState } from '@red/domain';
import { DossierStatesService } from '@services/entity-services/dossier-states.service';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

export interface AddEditDossierStateDialogData {
    readonly dossierState?: IDossierState;
    readonly dossierTemplateId: string;
}

@Component({
    templateUrl: './add-edit-dossier-state-dialog.component.html',
    styleUrls: ['./add-edit-dossier-state-dialog.component.scss'],
})
export class AddEditDossierStateDialogComponent extends BaseDialogComponent {
    readonly type = this.data.dossierState ? 'edit' : 'create';
    readonly titleTranslateParams = {
        type: this.type,
        name: this.data.dossierState?.name,
    };

    constructor(
        private readonly _dossierStatesService: DossierStatesService,
        protected readonly _dialogRef: MatDialogRef<AddEditDossierStateDialogComponent>,
        @Inject(MAT_DIALOG_DATA) readonly data: AddEditDossierStateDialogData,
    ) {
        super(_dialogRef, !!data.dossierState);
        this.form = this.#getForm();
        this.initialFormValue = this.form.getRawValue();
    }

    async save() {
        const dossierState: IDossierState = {
            dossierStatusId: this.data.dossierState?.dossierStatusId,
            dossierTemplateId: this.data.dossierTemplateId,
            ...this.form.getRawValue(),
        };

        this._loadingService.start();

        try {
            await this._dossierStatesService.createOrUpdate(dossierState);
            this._toaster.success(_('add-edit-dossier-state.success'), { params: { type: this.type } });
            this._dialogRef.close();
        } catch (e) {}

        this._loadingService.stop();
    }

    #getForm() {
        return this._formBuilder.group({
            name: [this.data.dossierState?.name, Validators.required],
            color: [this.data.dossierState?.color, Validators.required],
            rank: [this.data.dossierState?.rank, Validators.required],
        });
    }
}
