import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { IconButtonTypes, IqserDialogComponent } from '@iqser/common-ui';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { Dictionary, Dossier } from '@red/domain';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { DictionariesMapService } from '@services/entity-services/dictionaries-map.service';
import { ResizeAnnotationData, ResizeAnnotationResult } from '../../../utils/dialog-types';

@Component({
    templateUrl: './resize-annotation-dialog.component.html',
})
export class ResizeAnnotationDialogComponent
    extends IqserDialogComponent<ResizeAnnotationDialogComponent, ResizeAnnotationData, ResizeAnnotationResult>
    implements OnInit
{
    readonly #dossier: Dossier;
    readonly iconButtonTypes = IconButtonTypes;
    dictionaries: Dictionary[] = [];
    redaction: AnnotationWrapper;
    readonly form = this.#getForm();

    constructor(
        activeDossiersService: ActiveDossiersService,
        private readonly _dictionariesMapService: DictionariesMapService,
        private readonly _formBuilder: FormBuilder,
    ) {
        super();
        this.#dossier = activeDossiersService.find(this.data.dossierId);
        this.redaction = this.data.redaction;
    }

    get displayedDictionaryLabel() {
        const dictType = this.form.get('dictionary').value;
        if (dictType) {
            return this.dictionaries.find(d => d.type === dictType)?.label ?? null;
        }
        return null;
    }

    ngOnInit() {
        this.dictionaries = this._dictionariesMapService.get(this.#dossier.dossierTemplateId);
    }

    save() {
        const formValue = this.form.getRawValue();

        this.close({
            comment: formValue.comment,
            updateDictionary: this.redaction.entity.hasDictionary,
            addToAllDossiers: this.redaction.entity.hasDictionary,
        });
    }

    #getForm() {
        return this._formBuilder.group({
            comment: [null],
        });
    }
}
