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

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

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

    ngOnInit() {
        this.form = this._formBuilder.group({
            certificateName: [this.digitalSignature?.certificateName, Validators.required],
            kmsServiceEndpoint: [this.digitalSignature?.kmsServiceEndpoint, Validators.required],
            kmsRegion: [this.digitalSignature?.kmsRegion, Validators.required],
            kmsKeyId: [this.digitalSignature?.kmsKeyId, Validators.required],
            kmsAccessKey: [this.digitalSignature?.kmsAccessKey, Validators.required],
            kmsSecretKey: this.digitalSignature ? null : ['', Validators.required],
            certificate: this.digitalSignature ? null : ['', Validators.required],
        });
        this.initialFormValue = this.form.getRawValue();
        this.file = this.generateFile(this.digitalSignature?.certificateName, '.pem');
    }

    addRemoveCertificate(file: File | null): void {
        this.setCertificateName(file);
        if (file) {
            const fileReader = new FileReader();
            fileReader.onload = () => {
                const binaryContent = <string>fileReader.result;
                this.form.get('certificate').setValue(binaryContent);
            };
            fileReader.readAsBinaryString(file as Blob);
        } else {
            this.form.controls['certificate'].setValue('');
        }
    }

    save(): Promise<IKmsDigitalSignatureRequest> {
        const formValue = this.form.getRawValue();
        const digitalSignature: IKmsDigitalSignature = { ...formValue };

        if (!this.digitalSignature) {
            digitalSignature.certificate = window.btoa(digitalSignature.certificate);
        }

        return firstValueFrom(this._digitalSignatureService.saveKmsSignature(digitalSignature));
    }
}
