import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ActionConfig, CircleButtonTypes, EntitiesService, ListingService, LoadingService, Toaster } from '@iqser/common-ui';
import { Dossier, File, IFile } from '@red/domain';
import { PermissionsService } from '@services/permissions.service';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { ReanalysisService } from '@services/reanalysis.service';
import { combineLatest, firstValueFrom, map, Observable } from 'rxjs';
import { saveAsCSV } from '@utils/csv-utils';
import { UserService } from '@users/user.service';
import { ConfigService } from '../../config.service';
import { PrimaryFileAttributeService } from '@services/primary-file-attribute.service';
import { Router } from '@angular/router';
import { Roles } from '@users/roles';
import { SortingService } from '@iqser/common-ui/lib/sorting';
import { List, some } from '@iqser/common-ui/lib/utils';
import { TenantsService } from '@iqser/common-ui/lib/tenants';

@Component({
    selector: 'redaction-dossier-overview-screen-header [dossier] [upload]',
    templateUrl: './dossier-overview-screen-header.component.html',
})
export class DossierOverviewScreenHeaderComponent implements OnInit {
    @Input() dossier: Dossier;
    @Output() readonly upload = new EventEmitter<void>();
    readonly circleButtonTypes = CircleButtonTypes;
    readonly roles = Roles;
    actionConfigs: List<ActionConfig>;
    readonly downloadBtnDisabled$: Observable<boolean>;

    constructor(
        private readonly _toaster: Toaster,
        readonly configService: ConfigService,
        readonly router: Router,
        private readonly _userService: UserService,
        readonly listingService: ListingService<File>,
        readonly sortingService: SortingService<File>,
        readonly permissionsService: PermissionsService,
        readonly entitiesService: EntitiesService<IFile, File>,
        readonly tenantsService: TenantsService,
        private readonly _reanalysisService: ReanalysisService,
        private readonly _loadingService: LoadingService,
        private readonly _primaryFileAttributeService: PrimaryFileAttributeService,
    ) {
        const someNotProcessed$ = this.entitiesService.all$.pipe(some(file => !file.lastProcessed));
        this.downloadBtnDisabled$ = combineLatest([this.listingService.areSomeSelected$, someNotProcessed$]).pipe(
            map(([someSelected, someNotProcessed]) => someSelected || someNotProcessed),
        );
    }

    ngOnInit() {
        this.actionConfigs = this.configService.actionConfig(this.dossier.id, this.listingService.areSomeSelected$);
    }

    async reanalyseDossier() {
        this._loadingService.start();
        try {
            await this._reanalysisService.reanalyzeDossier(this.dossier, true);
            this._toaster.success(_('dossier-overview.reanalyse-dossier.success'));
        } catch (e) {
            this._toaster.error(_('dossier-overview.reanalyse-dossier.error'));
        }
        this._loadingService.stop();
    }

    async downloadDossierAsCSV() {
        const displayedEntities = await firstValueFrom(this.listingService.displayed$);
        const entities = this.sortingService.defaultSort(displayedEntities);
        const fileName = this.dossier.dossierName + '.export.csv';
        const mapper = (file?: File) => ({
            ...file,
            assignee: this._userService.getName(file.assignee) || '-',
            primaryAttribute: this._primaryFileAttributeService.getPrimaryFileAttributeValue(file, this.dossier.dossierTemplateId),
        });
        const fileFields = [
            'dossierId',
            'fileId',
            'filename',
            'primaryAttribute',
            'numberOfPages',
            'assignee',
            'workflowStatus',
            'processingStatus',
            'lastUpdated',
            'lastUploaded',
            'lastProcessed',
            'hasHints',
            'hasImages',
            'hasRedactions',
            'hasUpdates',
            'excluded',
        ];
        saveAsCSV(fileName, entities, fileFields, mapper);
    }
}
