import { Component, computed, ViewChild } from '@angular/core';
import { PermissionsService } from '@services/permissions.service';
import { InputWithActionComponent, LoadingService, Toaster } from '@iqser/common-ui';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { IPageRange } from '@red/domain';
import { ReanalysisService } from '@services/reanalysis.service';
import { FilePreviewStateService } from '../../services/file-preview-state.service';
import { extractPageRanges } from '@utils/page-ranges-mapper';

@Component({
    selector: 'redaction-page-exclusion',
    templateUrl: './page-exclusion.component.html',
    styleUrls: ['./page-exclusion.component.scss'],
})
export class PageExclusionComponent {
    readonly excludedRanges = computed(() => {
        const file = this._state.file();
        const sorted = [...file.excludedPages].sort((p1, p2) => p1 - p2);
        return this._toPageRange(sorted);
    });
    readonly canExcludePages = computed(() => this.permissionsService.canExcludePages(this._state.file(), this._state.dossier()));
    readonly noExcludedAndCantExclude = computed(() => !this.canExcludePages() && !this.excludedRanges().length);
    @ViewChild(InputWithActionComponent) private readonly _inputComponent: InputWithActionComponent;

    constructor(
        readonly permissionsService: PermissionsService,
        private readonly _reanalysisService: ReanalysisService,
        private readonly _toaster: Toaster,
        private readonly _loadingService: LoadingService,
        private readonly _state: FilePreviewStateService,
    ) {}

    async excludePagesRange(inputValue: string): Promise<void> {
        this._loadingService.start();
        const file = this._state.file();
        try {
            const pageRanges = extractPageRanges(inputValue, file);
            await this._reanalysisService.excludePages({ pageRanges }, file);
            this._inputComponent.reset();
        } catch (e) {
            this._toaster.error(_('file-preview.tabs.exclude-pages.error'));
        }
        this._loadingService.stop();
    }

    async includePagesRange(range: IPageRange): Promise<void> {
        this._loadingService.start();
        await this._reanalysisService.includePages({ pageRanges: [range] }, this._state.file());
        this._inputComponent.reset();
        this._loadingService.stop();
    }

    private _toPageRange(pages: number[]) {
        return pages.reduce((ranges: IPageRange[], page) => {
            if (!ranges.length) {
                return [{ startPage: page, endPage: page }];
            }

            if (page === Number(ranges[ranges.length - 1].endPage) + 1) {
                ranges[ranges.length - 1].endPage = page;
            } else {
                ranges.push({ startPage: page, endPage: page });
            }
            return ranges;
        }, []);
    }
}
