import { ChangeDetectionStrategy, Component, Input, OnChanges } from '@angular/core';
import { DossierTemplate, DossierTemplateStats } from '@red/domain';
import { BehaviorSubject, Observable } from 'rxjs';
import { DossierTemplateStatsService } from '@services/entity-services/dossier-template-stats.service';
import { switchMap } from 'rxjs/operators';
import { dossierTemplateStatusTranslations } from '@translations/dossier-template-status-translations';

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

    readonly translations = dossierTemplateStatusTranslations;
    readonly stats$: Observable<DossierTemplateStats>;
    private readonly _ngOnChanges$ = new BehaviorSubject<string>(undefined);

    constructor(readonly dossierTemplateStatsService: DossierTemplateStatsService) {
        this.stats$ = this._ngOnChanges$.pipe(switchMap(id => this.dossierTemplateStatsService.watch$(id)));
    }

    ngOnChanges() {
        if (this.dossierTemplate) {
            this._ngOnChanges$.next(this.dossierTemplate.id);
        }
    }
}
