import { Component, Input, OnChanges } from '@angular/core';
import { IqserPermissionsService } from '@iqser/common-ui';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import type { Dossier, File, User } from '@red/domain';
import { FilesMapService } from '@services/files/files-map.service';
import { PermissionsService } from '@services/permissions.service';
import { ReanalysisService } from '@services/reanalysis.service';
import { LongPressEvent } from '@shared/directives/long-press.directive';
import { Roles } from '@users/roles';
import { UserPreferenceService } from '@users/user-preference.service';
import { DossiersDialogService } from '../../services/dossiers-dialog.service';

@Component({
    selector: 'redaction-dossiers-listing-actions [dossier]',
    templateUrl: './dossiers-listing-actions.component.html',
})
export class DossiersListingActionsComponent implements OnChanges {
    readonly roles = Roles;
    readonly currentUser = getCurrentUser<User>();

    analysisForced: boolean;
    files: File[];
    displayReanalyseBtn = false;
    downloadBtnDisabled = false;

    @Input() dossier: Dossier;

    constructor(
        private readonly _reanalysisService: ReanalysisService,
        readonly permissionsService: PermissionsService,
        readonly iqserPermissionsService: IqserPermissionsService,
        readonly filesMapService: FilesMapService,
        private readonly _dialogService: DossiersDialogService,
        private readonly _userPreferenceService: UserPreferenceService,
    ) {}

    get canEditDossierDictionary() {
        return this.permissionsService.canEditDossierDictionary(this.dossier);
    }

    ngOnChanges() {
        this.files = this.filesMapService.get(this.dossier.id);
        this.downloadBtnDisabled = this.files.some(file => !file.lastProcessed);
        this.displayReanalyseBtn = this.permissionsService.displayReanalyseBtn(this.dossier) && this.analysisForced;
    }

    forceReanalysisAction($event: LongPressEvent) {
        this.analysisForced = !$event.touchEnd && this._userPreferenceService.isIqserDevMode;
    }

    openEditDossierDialog(dossierId: string): void {
        this._dialogService.openDialog('editDossier', { dossierId });
    }

    async reanalyseDossier(dossier: Dossier): Promise<void> {
        await this._reanalysisService.reanalyzeDossier(dossier);
    }
}
