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

@Component({
    selector: 'redaction-table-item [dossier]',
    templateUrl: './table-item.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TableItemComponent implements OnChanges {
    @Input() dossier!: Dossier;
    readonly stats$: Observable<DossierStats>;
    readonly #ngOnChanges$ = new BehaviorSubject<string>(undefined);

    constructor(readonly dossierStatsService: DossierStatsService) {
        this.stats$ = this.#ngOnChanges$.pipe(switchMap(dossierId => this.dossierStatsService.watch$(dossierId)));
    }

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