import { BaseFormComponent } from '@iqser/common-ui';
import { DigitalSignatureService } from '../../../services/digital-signature.service';
import { DigitalSignatureOption, DigitalSignatureOptions, IDigitalSignatureRequest } from '@red/domain';
import { firstValueFrom, Observable } from 'rxjs';

export abstract class BaseSignatureConfigurationComponent extends BaseFormComponent {
    file: File | null;

    protected constructor(
        protected readonly _digitalSignatureService: DigitalSignatureService,
        private readonly _selectedOption: DigitalSignatureOption,
    ) {
        super();
    }

    setCertificateName(file: File | null): void {
        if (file) {
            let name = file.name.split('.')[0];
            name = name.replace(/-/g, ' ');
            this.form.controls['certificateName'].setValue(name);
        } else {
            this.form.controls['certificateName'].setValue('');
        }
    }

    generateFile(certificateName: string, extension: '.p12' | '.pem'): File | null {
        if (certificateName) {
            return {
                name: certificateName.split(' ').join('-') + extension,
            } as File;
        }
        return null;
    }

    resetInitialFormValue(): void {
        this.initialFormValue = this.form.getRawValue();
    }

    deleteSignature(): Promise<unknown> {
        const observable: Observable<unknown> =
            this._selectedOption === DigitalSignatureOptions.PKCS
                ? this._digitalSignatureService.deleteSignature()
                : this._digitalSignatureService.deleteKmsSignature();
        return firstValueFrom(observable);
    }

    abstract addRemoveCertificate(file: File | null): void;

    abstract save(): Promise<IDigitalSignatureRequest | unknown>;
}
