import { Component, Input, OnChanges } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { CircleButtonType, CircleButtonTypes } from '@iqser/common-ui';
import { Action, ActionTypes, Dossier, File, ProcessingFileStatuses } from '@red/domain';
import { PermissionsService } from '@services/permissions.service';
import { LongPressEvent } from '@shared/directives/long-press.directive';
import { UserPreferenceService } from '@users/user-preference.service';
import { BulkActionsService } from '../../services/bulk-actions.service';

@Component({
    selector: 'redaction-dossier-overview-bulk-actions [dossier] [selectedFiles]',
    templateUrl: './dossier-overview-bulk-actions.component.html',
    styleUrls: ['./dossier-overview-bulk-actions.component.scss'],
})
export class DossierOverviewBulkActionsComponent implements OnChanges {
    #analysisForced: boolean;
    #canAssignToSelf: boolean;
    #canAssign: boolean;
    #canDelete: boolean;
    #canReanalyse: boolean;
    #canDisableAutoAnalysis: boolean;
    #canEnableAutoAnalysis: boolean;
    #canOcr: boolean;
    #canSetToNew: boolean;
    #canSetToUnderReview: boolean;
    #canSetToUnderApproval: boolean;
    #isReadyForApproval: boolean;
    #canApprove: boolean;
    #canUndoApproval: boolean;
    #canToggleAnalysis: boolean;
    #assignTooltip: string;
    #toggleAnalysisTooltip: string;
    #allFilesAreExcluded: boolean;
    #canMoveToSameState: boolean;
    @Input() dossier: Dossier;
    @Input() selectedFiles: File[];
    @Input() buttonType: CircleButtonType = CircleButtonTypes.default;
    @Input() maxWidth: number;
    buttons: Action[];

    constructor(
        private readonly _permissionsService: PermissionsService,
        private readonly _userPreferenceService: UserPreferenceService,
        private readonly _bulkActionsService: BulkActionsService,
    ) {}

    private get _buttons(): Action[] {
        const actions: Action[] = [
            {
                id: 'delete-files-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.delete(this.selectedFiles),
                tooltip: _('dossier-overview.bulk.delete'),
                icon: 'iqser:trash',
                show: this.#canDelete,
            },
            {
                id: 'assign-files-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.assign(this.selectedFiles),
                tooltip: this.#assignTooltip,
                icon: 'red:assign',
                show: this.#canAssign,
            },
            {
                id: 'assign-files-to-me-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.assignToMe(this.selectedFiles),
                tooltip: _('dossier-overview.assign-me'),
                icon: 'red:assign-me',
                show: this.#canAssignToSelf,
            },
            {
                id: 'to-new-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.setToNew(this.selectedFiles),
                tooltip: _('dossier-overview.back-to-new'),
                icon: 'red:undo',
                show: this.#canSetToNew,
            },
            {
                id: 'to-under-approval-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.setToUnderApproval(this.selectedFiles),
                tooltip: _('dossier-overview.under-approval'),
                icon: 'red:ready-for-approval',
                show: this.#canSetToUnderApproval,
            },
            {
                id: 'to-under-review-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.backToUnderReview(this.selectedFiles),
                tooltip: _('dossier-overview.under-review'),
                icon: 'red:undo',
                show: this.#canSetToUnderReview,
            },
            {
                id: 'download-files-btn',
                type: ActionTypes.downloadBtn,
                show: !this.selectedFiles.some(file => file.processingStatus === ProcessingFileStatuses.ERROR || !file.lastProcessed),
                files: this.selectedFiles,
                dossier: this.dossier,
            },
            {
                id: 'approve-files-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.approve(this.selectedFiles),
                disabled: !this.#canApprove,
                tooltip: this.#canApprove ? _('dossier-overview.approve') : _('dossier-overview.approve-disabled'),
                icon: 'red:approved',
                show: this.#isReadyForApproval,
            },
            {
                id: 'set-under-approval-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.setToUnderApproval(this.selectedFiles),
                tooltip: _('dossier-overview.under-approval'),
                icon: 'red:undo',
                show: this.#canUndoApproval,
            },
            {
                id: 'ocr-files-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.ocr(this.selectedFiles),
                tooltip: _('dossier-overview.ocr-file'),
                icon: 'iqser:ocr',
                show: this.#canOcr,
            },
            {
                id: 'reanalyse-files-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.reanalyse(this.selectedFiles),
                tooltip: _('dossier-overview.bulk.reanalyse'),
                icon: 'iqser:refresh',
                show: this.#canReanalyse && (this.#analysisForced || this.#canEnableAutoAnalysis),
            },
            {
                id: 'stop-automatic-analysis-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.toggleAutomaticAnalysis(this.selectedFiles),
                tooltip: _('dossier-overview.stop-auto-analysis'),
                icon: 'red:disable-analysis',
                show: this.#canDisableAutoAnalysis,
            },
            {
                id: 'start-automatic-analysis-btn',
                type: ActionTypes.circleBtn,
                action: () => this._bulkActionsService.toggleAutomaticAnalysis(this.selectedFiles),
                tooltip: _('dossier-overview.start-auto-analysis'),
                icon: 'red:enable-analysis',
                show: this.#canEnableAutoAnalysis,
            },
            {
                id: 'toggle-analysis-btn',
                type: ActionTypes.toggle,
                action: () => this._bulkActionsService.toggleAnalysis(this.selectedFiles, !this.#allFilesAreExcluded),
                tooltip: this.#toggleAnalysisTooltip,
                checked: !this.#allFilesAreExcluded,
                show: this.#canToggleAnalysis,
            },
        ];

        return actions.filter(btn => btn.show);
    }

    ngOnChanges() {
        this._setup();
    }

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

    private _setup() {
        if (!this.selectedFiles.length) {
            return;
        }
        const allFilesAreUnderReviewOrUnassigned = this.selectedFiles.reduce(
            (acc, file) => acc && (file.isUnderReview || file.isNew),
            true,
        );
        const allFilesAreUnderApproval = this.selectedFiles.reduce((acc, file) => acc && file.isUnderApproval, true);
        const allFilesAreApproved = this.selectedFiles.reduce((acc, file) => acc && file.isApproved, true);
        this.#allFilesAreExcluded = this.selectedFiles.reduce((acc, file) => acc && file.excluded, true);
        this.#canMoveToSameState = allFilesAreUnderReviewOrUnassigned || allFilesAreUnderApproval || allFilesAreApproved;

        this.#canAssign =
            this.#canMoveToSameState &&
            (this._permissionsService.canAssignUser(this.selectedFiles, this.dossier) ||
                this._permissionsService.canUnassignUser(this.selectedFiles, this.dossier));
        this.#canAssignToSelf = this.#canMoveToSameState && this._permissionsService.canAssignToSelf(this.selectedFiles, this.dossier);

        this.#canDelete = this._permissionsService.canSoftDeleteFile(this.selectedFiles, this.dossier);

        this.#canReanalyse = this._permissionsService.canReanalyseFile(this.selectedFiles, this.dossier);

        this.#canDisableAutoAnalysis = this._permissionsService.canDisableAutoAnalysis(this.selectedFiles, this.dossier);

        this.#canEnableAutoAnalysis = this._permissionsService.canEnableAutoAnalysis(this.selectedFiles, this.dossier);

        this.#canToggleAnalysis = this._permissionsService.canToggleAnalysis(this.selectedFiles, this.dossier);

        this.#canOcr = this._permissionsService.canOcrFile(this.selectedFiles, this.dossier);

        this.#canSetToNew = this._permissionsService.canSetToNew(this.selectedFiles, this.dossier);

        this.#canSetToUnderReview = this._permissionsService.canSetUnderReview(this.selectedFiles, this.dossier);

        this.#canSetToUnderApproval = this._permissionsService.canSetUnderApproval(this.selectedFiles, this.dossier);

        this.#isReadyForApproval = this._permissionsService.isReadyForApproval(this.selectedFiles, this.dossier);

        this.#canApprove = this._permissionsService.canBeApproved(this.selectedFiles, this.dossier);

        this.#canUndoApproval = this._permissionsService.canUndoApproval(this.selectedFiles, this.dossier);

        this.#assignTooltip = allFilesAreUnderApproval ? _('dossier-overview.assign-approver') : _('dossier-overview.assign-reviewer');

        this.#toggleAnalysisTooltip = this.#allFilesAreExcluded
            ? _('file-preview.toggle-analysis.enable')
            : _('file-preview.toggle-analysis.disable');

        this.buttons = this._buttons;
    }
}
