import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { ListingComponent, listingProvidersFactory, LoadingService } from '@iqser/common-ui';
import { Dossier, DOSSIER_TEMPLATE_ID } from '@red/domain';
import { ConfigService } from '../../services/config.service';
import { tap } from 'rxjs/operators';
import { ArchivedDossiersService } from '@services/dossiers/archived-dossiers.service';
import { Router } from '@angular/router';
import { OnAttach } from '@common-ui/utils';

@Component({
    selector: 'redaction-archived-dossiers-screen',
    templateUrl: './archived-dossiers-screen.component.html',
    providers: listingProvidersFactory(ArchivedDossiersScreenComponent),
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ArchivedDossiersScreenComponent extends ListingComponent<Dossier> implements OnInit, OnAttach {
    readonly tableColumnConfigs = this._configService.tableConfig;
    readonly tableHeaderLabel = _('archived-dossiers-listing.table-header.title');
    readonly computeFilters$ = this.entitiesService.all$.pipe(tap(() => this._computeAllFilters()));
    readonly #dossierTemplateId: string;

    constructor(
        private readonly _configService: ConfigService,
        private readonly _archivedDossiersService: ArchivedDossiersService,
        private readonly _loadingService: LoadingService,
        router: Router,
    ) {
        super();
        this.#dossierTemplateId = router.routerState.snapshot.root.firstChild.firstChild.paramMap.get(DOSSIER_TEMPLATE_ID);
        this.entitiesService.setEntities(this._archivedDossiersService.all.filter(d => d.dossierTemplateId === this.#dossierTemplateId));
    }

    ngOnInit(): void {
        this.addSubscription = this._archivedDossiersService.all$
            .pipe(tap(dossiers => this.entitiesService.setEntities(dossiers.filter(d => d.dossierTemplateId === this.#dossierTemplateId))))
            .subscribe();
        this._loadingService.stop();
    }

    ngOnAttach() {
        this._loadingService.stop();
    }

    private _computeAllFilters() {
        const filterGroups = this._configService.filterGroups(this.entitiesService.all);
        this.filterService.addFilterGroups(filterGroups);
    }
}
