import { ChangeDetectionStrategy, Component, HostListener, ViewChild } from '@angular/core';
import { Dictionary, DOSSIER_TEMPLATE_ID, ENTITY_TYPE } from '@red/domain';
import { DictionariesMapService } from '@services/entity-services/dictionaries-map.service';
import { ActivatedRoute } from '@angular/router';
import { getCurrentUser } from '@users/user.service';
import { PermissionsService } from '@services/permissions.service';
import { AddEditEntityComponent } from '@shared/components/add-edit-entity/add-edit-entity.component';
import { getConfig, IconButtonTypes } from '@iqser/common-ui';
import { Observable } from 'rxjs';
import { IqserEventTarget } from '@iqser/common-ui/lib/utils';

@Component({
    selector: 'redaction-entity-info',
    templateUrl: './entity-info.component.html',
    styleUrls: ['./entity-info.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EntityInfoComponent {
    @ViewChild(AddEditEntityComponent) private readonly _addEditEntityComponent: AddEditEntityComponent;
    readonly currentUser = getCurrentUser();
    readonly entity$: Observable<Dictionary>;
    readonly dossierTemplateId: string;
    readonly config = getConfig();
    readonly iconButtonTypes = IconButtonTypes;

    constructor(route: ActivatedRoute, dictionariesMapService: DictionariesMapService, readonly permissionsService: PermissionsService) {
        this.dossierTemplateId = route.parent.snapshot.paramMap.get(DOSSIER_TEMPLATE_ID);
        const entityType = route.parent.snapshot.paramMap.get(ENTITY_TYPE);
        this.entity$ = dictionariesMapService.watch$(this.dossierTemplateId, entityType);
    }

    get disabled(): boolean {
        return !this._addEditEntityComponent || this._addEditEntityComponent.form?.invalid || !this._addEditEntityComponent.changed;
    }

    get changed(): boolean {
        return this._addEditEntityComponent.changed;
    }

    async save(): Promise<void> {
        try {
            await this._addEditEntityComponent.save();
        } catch (e) {
            console.error(e);
        }
    }

    revert(): void {
        this._addEditEntityComponent.revert();
    }

    @HostListener('window:keydown.Enter', ['$event'])
    async onEnter(event: KeyboardEvent): Promise<void> {
        event?.stopImmediatePropagation();
        const node = (event.target as IqserEventTarget).localName;
        if (this._addEditEntityComponent.valid && !this.disabled && this._addEditEntityComponent.changed && node !== 'textarea') {
            await this.save();
        }
    }
}
