/*
 * 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.cryptolib.certificates.configuration;

import com.scytl.cryptolib.api.exceptions.CryptoLibException;
import com.scytl.cryptolib.certificates.constants.X509CertificateConstants;
import com.scytl.cryptolib.commons.configuration.PolicyFromPropertiesHelper;
import com.scytl.cryptolib.primitives.securerandom.configuration.ConfigSecureRandomAlgorithmAndProvider;

/**
 * Implementation of the {@link X509CertificateGeneratorPolicy} interface, to
 * retrieve the X509 certificate generator cryptographic policy from a given
 * properties input.
 * <P>
 * Instances of this class are immutable.
 */
public class X509CertificateGeneratorPolicyFromProperties implements
        X509CertificateGeneratorPolicy {

    private ConfigX509CertificateAlgorithmAndProvider _algorithmAndProvider;

    private final ConfigSecureRandomAlgorithmAndProvider _secureRandomAlgorithmAndProvider;

    /**
     * Creates a X509 certificate generator cryptographic policy using
     * properties which are read from the properties file at the specified path.
     * 
     * @param path
     *            a path of cryptographic policy file.
     * @throws CryptoLibException
     *             if path or properties are invalid.
     */
    public X509CertificateGeneratorPolicyFromProperties(final String path) {

        try {
            PolicyFromPropertiesHelper helper =
                new PolicyFromPropertiesHelper(path);

            _algorithmAndProvider =
                ConfigX509CertificateAlgorithmAndProvider
                    .valueOf(helper
                        .getNotBlankPropertyValue(X509CertificateConstants.CERTIFICATE_ALGORITHM_PROVIDER_PROPERTY_NAME));

            _secureRandomAlgorithmAndProvider =
                ConfigSecureRandomAlgorithmAndProvider
                    .valueOf(helper
                        .getNotBlankOSDependentPropertyValue("certificates.x509certificate.securerandom"));

        } catch (IllegalArgumentException e) {
            throw new CryptoLibException("Illegal property value", e);
        }
    }

    @Override
    public ConfigX509CertificateAlgorithmAndProvider getCertificateAlgorithmAndProvider() {

        return _algorithmAndProvider;
    }

    @Override
    public ConfigSecureRandomAlgorithmAndProvider getSecureRandomAlgorithmAndProvider() {
        return _secureRandomAlgorithmAndProvider;
    }
}
