import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { DictionaryManagerComponent } from '@shared/components/dictionary-manager/dictionary-manager.component';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { IqserPermissionsService, LoadingService } from '@iqser/common-ui';
import { BehaviorSubject } from 'rxjs';
import { DICTIONARY_TO_ENTRY_TYPE_MAP, DICTIONARY_TYPE_KEY_MAP, DictionaryType, DOSSIER_TEMPLATE_ID, ENTITY_TYPE, User } from '@red/domain';
import { PermissionsService } from '@services/permissions.service';
import { Roles } from '@users/roles';
import { NGXLogger } from 'ngx-logger';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { getParam, List } from '@iqser/common-ui/lib/utils';

@Component({
    templateUrl: './dictionary-screen.component.html',
    styleUrls: ['./dictionary-screen.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DictionaryScreenComponent implements OnInit {
    readonly #dossierTemplateId = getParam(DOSSIER_TEMPLATE_ID);
    @ViewChild('dictionaryManager', { static: false })
    private readonly _dictionaryManager: DictionaryManagerComponent;
    readonly currentUser = getCurrentUser<User>();
    readonly roles = Roles;
    readonly initialEntries$ = new BehaviorSubject<string[]>([]);
    isLeavingPage = false;
    readonly type: DictionaryType;
    readonly entityType = getParam(ENTITY_TYPE);

    constructor(
        route: ActivatedRoute,
        readonly permissionsService: PermissionsService,
        readonly iqserPermissionsService: IqserPermissionsService,
        private readonly _loadingService: LoadingService,
        private readonly _dictionaryService: DictionaryService,
        private readonly _logger: NGXLogger,
    ) {
        this.type = route.snapshot.routeConfig.path as DictionaryType;
    }

    get changed() {
        return this._dictionaryManager.editor.hasChanges;
    }

    async ngOnInit() {
        await this.#loadEntries();
    }

    async save() {
        this._logger.info('[EDITOR] Saving...');
        const entries = this._dictionaryManager.editor?.currentEntries;

        this._loadingService.start();
        try {
            await this._dictionaryService.saveEntries(
                entries,
                this.initialEntries$.value,
                this.#dossierTemplateId,
                this.entityType,
                null,
                true,
                DICTIONARY_TO_ENTRY_TYPE_MAP[this.type],
            );
            await this.#loadEntries();
        } catch (e) {
            this._loadingService.stop();
        }
    }

    async #loadEntries() {
        this._loadingService.start();
        try {
            const data = await this._dictionaryService.getForType(this.#dossierTemplateId, this.entityType);
            const entries: List = data[DICTIONARY_TYPE_KEY_MAP[this.type]];
            this.initialEntries$.next([...entries].sort((str1, str2) => str1.localeCompare(str2, undefined, { sensitivity: 'accent' })));
        } catch (e) {
            this.initialEntries$.next([]);
        } finally {
            this._loadingService.stop();
        }
    }
}
