/*
 * 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.primitives.derivation.configuration;

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

/**
 * Implementation of the {@link DerivationPolicy} interface, which reads values
 * from a properties input.
 * <P>
 * Instances of this class are immutable.
 */
public final class DerivationPolicyFromProperties implements
        DerivationPolicy {

    private final ConfigKDFDerivationParameters _kdfDerivationParameters;

    private final ConfigPBKDFDerivationParameters _pbkdfDerivationParameters;

    private final ConfigSecureRandomAlgorithmAndProvider _secureRandomAlgorithmAndProvider;

    /**
     * Instantiates a property provider that reads properties from the specified
     * path.
     * 
     * @param path
     *            The path where the properties are read from.
     * @throws CryptoLibException
     *             if the path is blank or incorrect.
     */
    public DerivationPolicyFromProperties(final String path) {

        try {

            PolicyFromPropertiesHelper helper =
                new PolicyFromPropertiesHelper(path);

            _kdfDerivationParameters =
                ConfigKDFDerivationParameters.valueOf(helper
                    .getNotBlankPropertyValue("primitives.kdfderivation"));

            _pbkdfDerivationParameters =
                ConfigPBKDFDerivationParameters
                    .valueOf(helper
                        .getNotBlankPropertyValue("primitives.pbkdfderivation"));

            _secureRandomAlgorithmAndProvider =
                ConfigSecureRandomAlgorithmAndProvider
                    .valueOf(helper
                        .getNotBlankOSDependentPropertyValue("primitives.pbkdfderivation.securerandom"));

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

    @Override
    public ConfigKDFDerivationParameters getKDFDerivationParameters() {
        return _kdfDerivationParameters;
    }

    @Override
    public ConfigPBKDFDerivationParameters getPBKDFDerivationParameters() {
        return _pbkdfDerivationParameters;
    }

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