import { ChangeDetectionStrategy, Component, Input, OnChanges } from '@angular/core';
import { Dossier, DossierStats } from '@red/domain';
import { DossierStatsService } from '@services/dossiers/dossier-stats.service';
import { BehaviorSubject, Observable } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { getConfig } from '@iqser/common-ui';

@Component({
    selector: 'redaction-table-item [dossier]',
    templateUrl: './table-item.component.html',
    styleUrls: ['./table-item.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TableItemComponent implements OnChanges {
    @Input() dossier!: Dossier;

    readonly stats$: Observable<DossierStats>;
    readonly isDocumine = getConfig().IS_DOCUMINE;
    readonly #ngOnChanges$ = new BehaviorSubject<string>(undefined);

    constructor(readonly dossierStatsService: DossierStatsService) {
        this.stats$ = this.#ngOnChanges$.pipe(
            switchMap(dossierId => this.dossierStatsService.watch$(dossierId)),
            // TODO required for sorting the dossier table - fix me Baby one more time!
            tap(stats => {
                this.dossier.changedDate = stats.fileManipulationDate;
            }),
        );
    }

    ngOnChanges() {
        if (this.dossier) {
            this.#ngOnChanges$.next(this.dossier.id);
        }
    }
}
