import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { DOSSIER_TEMPLATE_ID, ENTITY_TYPE } from '@red/domain';
import { Router } from '@angular/router';
import { firstValueFrom, Observable } from 'rxjs';
import { AdminDialogService } from '../services/admin-dialog.service';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { LoadingService } from '@iqser/common-ui';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';
import { DictionariesMapService } from '@services/entity-services/dictionaries-map.service';
import { map } from 'rxjs/operators';
import { PermissionsService } from '@services/permissions.service';
import { getParam } from '@iqser/common-ui/lib/utils';
import { TenantsService } from '@iqser/common-ui/lib/tenants';

@Component({
    templateUrl: './base-entity-screen.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BaseEntityScreenComponent implements OnInit {
    readonly #dossierTemplateId = getParam(DOSSIER_TEMPLATE_ID);
    readonly #entityType = getParam(ENTITY_TYPE);
    readonly disabledItems$: Observable<string[]>;
    readonly canDeleteEntity$: Observable<boolean>;

    constructor(
        private readonly _router: Router,
        dictionaryMapService: DictionariesMapService,
        private readonly _loadingService: LoadingService,
        private readonly _dialogService: AdminDialogService,
        private readonly _dictionaryService: DictionaryService,
        private readonly _permissionsService: PermissionsService,
        private readonly _tenantsService: TenantsService,
        private readonly _dossierTemplatesService: DossierTemplatesService,
    ) {
        const entity$ = dictionaryMapService.watch$(this.#dossierTemplateId, this.#entityType);
        this.canDeleteEntity$ = entity$.pipe(map(entity => this._permissionsService.canDeleteEntities(entity)));
        this.disabledItems$ = entity$.pipe(
            map(entity =>
                entity.hasDictionary && !entity.dossierDictionaryOnly ? [] : ['dictionary', 'false-positive', 'false-recommendations'],
            ),
        );
    }

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

    openDeleteDictionariesDialog() {
        this._dialogService.openDialog('confirm', null, async () => {
            this._loadingService.start();
            const dossierTemplate = this._dossierTemplatesService.find(this.#dossierTemplateId);
            await firstValueFrom(this._dictionaryService.deleteDictionaries([this.#entityType], this.#dossierTemplateId));
            await this._router.navigate([`/${this._tenantsService.activeTenantId}/${dossierTemplate.routerLink}/entities`]);
            this._loadingService.stop();
        });
    }
}
