/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.crypto.configuration;

import java.security.PrivateKey;
import java.security.PublicKey;

import com.scytl.cryptolib.api.certificates.CertificatesServiceAPI;
import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.certificates.bean.CertificateData;
import com.scytl.cryptolib.certificates.bean.RootCertificateData;
import com.scytl.cryptolib.certificates.cryptoapi.CryptoAPIX509Certificate;

/**
 * Generates a x509 certificate.
 */
public class X509CertificateGenerator {
    private final CertificatesServiceAPI certificatesService;

    private final CertificateDataBuilder certificateDataBuilder;

    public X509CertificateGenerator(final CertificatesServiceAPI certificatesService,
                                    final CertificateDataBuilder certificateDataBuilder) {
    	this.certificatesService = certificatesService;
    	this.certificateDataBuilder = certificateDataBuilder;

    }

    public CryptoAPIX509Certificate generate(final CertificateParameters certificateParameters,
            final PublicKey subjectPublicKey, final PrivateKey caPrivateKey)
            throws GeneralCryptoLibException {
        CertificateData certificateData = certificateDataBuilder.build(subjectPublicKey, certificateParameters);

        CryptoAPIX509Certificate certificate = null;

        switch (certificateParameters.getType()) {
        case ROOT:
            RootCertificateData rootCertificateData = certificateData;
            certificate = certificatesService.createRootAuthorityX509Certificate(rootCertificateData, caPrivateKey);
            break;
        case INTERMEDIATE:
            certificate =
                certificatesService.createIntermediateAuthorityX509Certificate(certificateData, caPrivateKey);
            break;
        case SIGN:
            certificate = certificatesService.createSignX509Certificate(certificateData, caPrivateKey);
            break;
        case ENCRYPTION:
            certificate = certificatesService.createEncryptionX509Certificate(certificateData, caPrivateKey);
            break;
        default:
            break;

        }

        return certificate;
    }
}
