import { Component, Inject, OnInit } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import { Dossier, File, IFileAttributeConfig } from '@red/domain';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { FileAttributesService } from '@services/entity-services/file-attributes.service';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { FilesService } from '@services/files/files.service';
import { BaseDialogComponent } from '@iqser/common-ui';
import { firstValueFrom } from 'rxjs';
import dayjs from 'dayjs';

@Component({
    templateUrl: './document-info-dialog.component.html',
})
export class DocumentInfoDialogComponent extends BaseDialogComponent implements OnInit {
    form: UntypedFormGroup;
    attributes: IFileAttributeConfig[];

    private readonly _dossier: Dossier;

    constructor(
        activeDossiersService: ActiveDossiersService,
        private readonly _fileAttributesService: FileAttributesService,
        private readonly _filesService: FilesService,
        protected readonly _dialogRef: MatDialogRef<DocumentInfoDialogComponent>,
        @Inject(MAT_DIALOG_DATA) readonly file: File,
    ) {
        super(_dialogRef);
        this._dossier = activeDossiersService.find(this.file.dossierId);
    }

    async ngOnInit() {
        this.attributes = (
            await firstValueFrom(this._fileAttributesService.loadFileAttributesConfig(this._dossier.dossierTemplateId))
        ).fileAttributeConfigs.filter(attr => attr.editable);
        this.form = this._getForm();
        this.initialFormValue = this.form.getRawValue();
    }

    async save() {
        const attributeIdToValue = {
            ...this.file.fileAttributes?.attributeIdToValue,
            ...this._mapFormValues(this.form.getRawValue()),
        };
        await firstValueFrom(this._fileAttributesService.setFileAttributes({ attributeIdToValue }, this.file.dossierId, this.file.fileId));
        await this._filesService.reload(this.file.dossierId, this.file);
        this._dialogRef.close(true);
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group(
            this.attributes.reduce((acc, attr) => {
                const attrValue = this.file.fileAttributes?.attributeIdToValue[attr.id];
                return {
                    ...acc,
                    [attr.id]: [this._isDate(attr.id) ? attrValue && dayjs(attrValue).toDate() : attrValue],
                };
            }, {}),
        );
    }

    private _isDate(attrId: string) {
        return this.attributes.find(a => a.id === attrId).type === 'DATE';
    }

    private _mapFormValues(formValue) {
        return Object.keys(formValue).reduce((acc, key) => {
            const crtValue = formValue[key];
            return {
                ...acc,
                [key]: this._isDate(key) ? crtValue && dayjs(crtValue).format('YYYY-MM-DD') : crtValue,
            };
        }, {});
    }
}
