import { Component, Inject, OnInit, signal } from '@angular/core';
import { BaseDialogComponent, CircleButtonTypes } from '@iqser/common-ui';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { RssService } from '@services/files/rss.service';
import { IFile, RssEntry } from '@red/domain';
import { firstValueFrom } from 'rxjs';
import { FilesMapService } from '@services/files/files-map.service';
import { UserPreferenceService } from '@users/user-preference.service';

interface RssData {
    file: IFile;
}

@Component({
    templateUrl: './rss-dialog.component.html',
    styleUrls: ['./rss-dialog.component.scss'],
})
export class RssDialogComponent extends BaseDialogComponent implements OnInit {
    readonly circleButtonTypes = CircleButtonTypes;

    readonly rssData = signal<RssEntry | undefined>(undefined);

    constructor(
        protected readonly _dialogRef: MatDialogRef<RssDialogComponent>,
        private readonly _rssService: RssService,
        readonly userPreferences: UserPreferenceService,
        private readonly _filesMapService: FilesMapService,
        @Inject(MAT_DIALOG_DATA) readonly data: RssData,
    ) {
        super(_dialogRef);
    }

    async ngOnInit(): Promise<void> {
        await this.#loadData();
    }

    originalOrder = (): number => 0;

    exportJSON() {
        return firstValueFrom(this._rssService.exportJSON(this.data.file.dossierId, this.data.file.fileId, this.data.file.filename));
    }

    exportXML() {
        return firstValueFrom(this._rssService.exportXML(this.data.file.dossierId, this.data.file.fileId, this.data.file.filename));
    }

    async exportAllInDossier() {
        const allFilesInDossier = this._filesMapService.get(this.data.file.dossierId);
        for (const file of allFilesInDossier) {
            await firstValueFrom(this._rssService.exportJSON(file.dossierId, file.fileId, file.filename));
            await firstValueFrom(this._rssService.exportXML(file.dossierId, file.fileId, file.filename));
        }
    }

    save() {
        return this.exportJSON();
    }

    async undo(originalKey: string) {
        this._loadingService.start();
        await firstValueFrom(this._rssService.revertOverride(this.data.file.dossierId, this.data.file.fileId, [originalKey]));
        await this.#loadData();
    }

    async saveEdit(event: string, originalKey: string) {
        this._loadingService.start();
        await firstValueFrom(this._rssService.override(this.data.file.dossierId, this.data.file.fileId, { [originalKey]: event }));
        await this.#loadData();
    }

    async #loadData(): Promise<void> {
        this._loadingService.start();
        const rssData = await firstValueFrom(this._rssService.getRSSData(this.data.file.dossierId, this.data.file.fileId));
        this.rssData.set(rssData);
        this._loadingService.stop();
    }
}
