import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { BaseSignatureConfigurationComponent } from '../base-signature-configuration-component';
import { DigitalSignatureOptions, IPkcsDigitalSignature, IPkcsDigitalSignatureRequest } from '@red/domain';
import { firstValueFrom } from 'rxjs';
import { DigitalSignatureService } from '../../../../services/digital-signature.service';
import { lastIndexOfEnd } from '../../../../../../utils';

@Component({
    selector: 'redaction-pkcs-signature-configuration',
    templateUrl: './pkcs-signature-configuration.component.html',
    styleUrls: ['./pkcs-signature-configuration.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PkcsSignatureConfigurationComponent extends BaseSignatureConfigurationComponent implements OnInit {
    @Input() digitalSignature!: IPkcsDigitalSignatureRequest;

    constructor(protected readonly _digitalSignatureService: DigitalSignatureService, private readonly _formBuilder: UntypedFormBuilder) {
        super(_digitalSignatureService, DigitalSignatureOptions.PKCS);
    }

    ngOnInit() {
        this.form = this._formBuilder.group({
            certificateName: [this.digitalSignature?.certificateName, Validators.required],
            password: this.digitalSignature ? null : ['', Validators.required],
            contactInfo: [this.digitalSignature?.contactInfo],
            location: [this.digitalSignature?.location],
            reason: [this.digitalSignature?.reason],
            base64EncodedPrivateKey: this.digitalSignature ? null : ['', Validators.required],
        });
        this.resetInitialFormValue();
        this.file = this.generateFile(this.digitalSignature?.certificateName, '.p12');
    }

    addRemoveCertificate(file: File | null): void {
        this.setCertificateName(file);
        if (file) {
            const fileReader = new FileReader();
            fileReader.onload = () => {
                const dataUrl = <string>fileReader.result;
                const actualBase64Value = dataUrl.substring(lastIndexOfEnd(dataUrl, ';base64,'));
                this.form.get('base64EncodedPrivateKey').setValue(actualBase64Value);
            };
            fileReader.readAsDataURL(file as Blob);
        } else {
            this.form.controls['base64EncodedPrivateKey'].setValue('');
        }
    }

    save(): Promise<IPkcsDigitalSignatureRequest | unknown> {
        const formValue = this.form.getRawValue();
        const digitalSignature: IPkcsDigitalSignature = { ...formValue };

        const observable = this.digitalSignature
            ? this._digitalSignatureService.updateSignature(digitalSignature)
            : this._digitalSignatureService.saveSignature(digitalSignature);
        return firstValueFrom(observable);
    }
}
