/*
 * 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.symmetric.key.configuration;

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

/**
 * An implementation of
 * {@link com.scytl.cryptolib.symmetric.key.configuration.SymmetricKeyPolicy}
 * which is read from a properties file.
 * <P>
 * Instances of this class are immutable.
 */
public final class SymmetricKeyPolicyFromProperties implements
        SymmetricKeyPolicy {

    private final ConfigSecretKeyAlgorithmAndSpec _configSecretKeyAlgorithmAndSpec;

    private final ConfigHmacSecretKeyAlgorithmAndSpec _configHmacSecretKeyAlgorithmAndSpec;

    private final ConfigSecureRandomAlgorithmAndProvider _secureRandomAlgorithmAndProvider;

    /**
     * Creates a symmetric key policy using properties which are read from the
     * properties file at the specified path.
     * 
     * @param path
     *            the path of the properties file to be read.
     * @throws CryptoLibException
     *             if path is invalid or properties are invalid.
     */
    public SymmetricKeyPolicyFromProperties(final String path) {

        try {
            PolicyFromPropertiesHelper helper =
                new PolicyFromPropertiesHelper(path);

            _configSecretKeyAlgorithmAndSpec =
                ConfigSecretKeyAlgorithmAndSpec
                    .valueOf(helper
                        .getNotBlankPropertyValue("symmetric.encryptionsecretkey"));

            _configHmacSecretKeyAlgorithmAndSpec =
                ConfigHmacSecretKeyAlgorithmAndSpec.valueOf(helper
                    .getNotBlankPropertyValue("symmetric.macsecretkey"));

            _secureRandomAlgorithmAndProvider =
                ConfigSecureRandomAlgorithmAndProvider
                    .valueOf(helper
                        .getNotBlankOSDependentPropertyValue("symmetric.key.securerandom"));

        } catch (IllegalArgumentException e) {
            throw new CryptoLibException(
                "An IllegalArgumentException exception was thrown while trying to construct a symmetric key policy from a properties file. The path was "
                    + path, e);
        }
    }

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

    @Override
    public ConfigSecretKeyAlgorithmAndSpec getSecretKeyAlgorithmAndSpec() {
        return _configSecretKeyAlgorithmAndSpec;
    }

    @Override
    public ConfigHmacSecretKeyAlgorithmAndSpec getHmacSecretKeyAlgorithmAndSpec() {
        return _configHmacSecretKeyAlgorithmAndSpec;
    }
}
