import { ChangeDetectionStrategy, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { PrimaryFileAttributeService } from '@services/primary-file-attribute.service';
import { FileAttributes } 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';

interface PartialFile {
    readonly isError: boolean;
    readonly isInitialProcessing: boolean;
    readonly filename: string;
    readonly numberOfPages: number;
    readonly excludedPages: number[];
    readonly lastOCRTime?: string;
    readonly fileAttributes: FileAttributes;
    readonly lastManualChangeDate?: string;
}

interface FileNameColumnContext {
    primaryAttribute: string;
}

@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: PartialFile;
    @Input() dossierTemplateId: string;

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

    ngOnInit(): void {
        const primaryAttribute$ = combineLatest([this._fileAttributeService.fileAttributesConfig$, this.#reloadAttribute]).pipe(
            map(() => this._primaryFileAttributeService.getPrimaryFileAttributeValue(this.file, this.dossierTemplateId)),
        );
        super._initContext({
            primaryAttribute: primaryAttribute$,
        });
    }

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