import { ChangeDetectionStrategy, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { PrimaryFileAttributeService } from '@services/primary-file-attribute.service';
import { Dossier, File, IFileAttributeConfig, TrashFile } from '@red/domain';
import { FileAttributesService } from '@services/entity-services/file-attributes.service';
import { combineLatest, map, ReplaySubject } from 'rxjs';
import { ContextComponent } from '@iqser/common-ui/lib/utils';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';

interface FileNameColumnContext {
    primaryAttribute: IFileAttributeConfig;
    ocrByDefault: boolean;
}

@Component({
    selector: 'redaction-file-name-column',
    templateUrl: './file-name-column.component.html',
    styleUrls: ['./file-name-column.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FileNameColumnComponent extends ContextComponent<FileNameColumnContext> implements OnInit, OnChanges {
    readonly #reloadAttribute = new ReplaySubject<void>(1);
    @Input() file?: File | TrashFile;
    @Input() dossier: Dossier;
    @Input() dossierTemplateId: string;

    constructor(
        private readonly _fileAttributeService: FileAttributesService,
        private readonly _primaryFileAttributeService: PrimaryFileAttributeService,
        private readonly _dossierTemplateService: DossierTemplatesService,
    ) {
        super();
    }

    ngOnInit(): void {
        const primaryAttribute$ = combineLatest([this._fileAttributeService.fileAttributesConfig$, this.#reloadAttribute]).pipe(
            map(() => this.#findPrimaryAttribute()),
        );
        const ocrByDefault$ = this._dossierTemplateService.get(this.dossierTemplateId).pipe(map(template => template.ocrByDefault));
        super._initContext({
            primaryAttribute: primaryAttribute$,
            ocrByDefault: ocrByDefault$,
        });
    }

    ngOnChanges(changes: SimpleChanges): void {
        if (changes.file) {
            this.#reloadAttribute.next();
        }
    }

    get defaultFile() {
        return this.file as File;
    }

    #findPrimaryAttribute() {
        if (this.file.softDeletedTime) {
            const primaryAttribute = this._primaryFileAttributeService.getPrimaryFileAttributeValue(this.file, this.dossierTemplateId);
            return { label: primaryAttribute } as IFileAttributeConfig;
        }
        const fileAttributes = this._fileAttributeService.getFileAttributeConfig(this.dossierTemplateId);
        return fileAttributes?.fileAttributeConfigs.find(a => a.primaryAttribute);
    }
}
