import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { IconButtonTypes, IqserPermissionsService, LoadingService, Toaster } from '@iqser/common-ui';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { RouterHistoryService } from '@services/router-history.service';
import { DigitalSignatureService } from '../../services/digital-signature.service';
import { firstValueFrom } from 'rxjs';
import { AdminDialogService } from '../../services/admin-dialog.service';
import { PkcsSignatureConfigurationComponent } from '../../dialogs/configure-digital-signature-dialog/form/pkcs-signature-configuration/pkcs-signature-configuration.component';
import { KmsSignatureConfigurationComponent } from '../../dialogs/configure-digital-signature-dialog/form/kms-signature-configuration/kms-signature-configuration.component';
import { DigitalSignatureOptions, IKmsDigitalSignatureRequest, IPkcsDigitalSignatureRequest, User } from '@red/domain';
import { Roles } from '@users/roles';
import { getCurrentUser } from '@iqser/common-ui/lib/users';

@Component({
    selector: 'redaction-digital-signature-screen',
    templateUrl: './digital-signature-screen.component.html',
    styleUrls: ['./digital-signature-screen.component.scss'],
})
export class DigitalSignatureScreenComponent implements OnInit {
    @ViewChild(PkcsSignatureConfigurationComponent) pkcsSignatureConfigurationComponent: PkcsSignatureConfigurationComponent;
    @ViewChild(KmsSignatureConfigurationComponent) kmsSignatureConfigurationComponent: KmsSignatureConfigurationComponent;

    readonly certificateType = DigitalSignatureOptions;
    readonly iconButtonTypes = IconButtonTypes;
    readonly roles = Roles;
    readonly currentUser = getCurrentUser<User>();

    digitalSignature: IPkcsDigitalSignatureRequest | IKmsDigitalSignatureRequest;

    constructor(
        private readonly _toaster: Toaster,
        private readonly _loadingService: LoadingService,
        private readonly _digitalSignatureService: DigitalSignatureService,
        private readonly _dialogService: AdminDialogService,
        private readonly _changeDetectorRef: ChangeDetectorRef,
        readonly routerHistoryService: RouterHistoryService,
        readonly permissionsService: IqserPermissionsService,
    ) {}

    get disabled(): boolean {
        //TODO remove second check when the update endpoint will be available for KMS signature
        return this.activeComponent?.disabled || this.currentCertificateType === DigitalSignatureOptions.KMS;
    }

    get currentCertificateType() {
        if (!this.digitalSignature) {
            return;
        }
        return 'contactInfo' in this.digitalSignature ? DigitalSignatureOptions.PKCS : DigitalSignatureOptions.KMS;
    }

    get activeComponent() {
        return this.currentCertificateType === DigitalSignatureOptions.PKCS
            ? this.pkcsSignatureConfigurationComponent
            : this.kmsSignatureConfigurationComponent;
    }

    async ngOnInit(): Promise<void> {
        await this.loadDigitalSignature();
    }

    async removeDigitalSignature(): Promise<void> {
        this._loadingService.start();
        try {
            await this.activeComponent.deleteSignature();
            await this.loadDigitalSignature();
            this._toaster.success(_('digital-signature-screen.action.delete-success'));
        } catch (error) {
            console.error(error);
            this._toaster.error(_('digital-signature-screen.action.delete-error'));
        }
    }

    async saveDigitalSignature(): Promise<void> {
        try {
            await this.activeComponent.save();
            this.activeComponent.resetInitialFormValue();
            this._toaster.success(_('digital-signature-screen.action.save-success'));
        } catch (error) {
            this._toaster.error(_('digital-signature-screen.action.save-error'));
        }
    }

    openConfigureCertificate(): void {
        const dialogRef = this._dialogService.openDialog('configureCertificate');
        firstValueFrom(dialogRef.afterClosed()).then(async res => {
            if (res) {
                await this.loadDigitalSignature();
            }
        });
    }

    async loadDigitalSignature(): Promise<void> {
        this._loadingService.start();
        this.digitalSignature = await firstValueFrom(this._digitalSignatureService.getSignature());
        this._loadingService.stop();
        this._changeDetectorRef.detectChanges();
    }
}
