/*
 * 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.config.model.authentication.service;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.primitives.securerandom.configuration.SecureRandomPolicyFromProperties;
import com.scytl.cryptolib.primitives.securerandom.factory.CryptoRandomString;
import com.scytl.cryptolib.primitives.securerandom.factory.SecureRandomFactory;
import com.scytl.products.ov.config.exceptions.SingleSecretAuthenticationKeyGeneratorException;
import com.scytl.products.ov.config.model.authentication.AuthenticationKey;
import com.scytl.products.ov.config.model.authentication.AuthenticationKeyGenerator;
import com.scytl.products.ov.config.model.authentication.StartVotingKey;
import com.scytl.products.ov.constants.Constants;

public class SingleSecretAuthenticationKeyGenerator implements AuthenticationKeyGenerator {

    private final CryptoRandomString cryptoRandomString;

    public SingleSecretAuthenticationKeyGenerator() {

        final String path = com.scytl.cryptolib.commons.constants.Constants.CRYPTOLIB_POLICY_PROPERTIES_FILE_PATH;
        SecureRandomFactory secureRandomFactory = new SecureRandomFactory(new SecureRandomPolicyFromProperties(path));
        cryptoRandomString = secureRandomFactory.createStringRandom(Constants.SVK_ALPHABET);
    }

    /**
     * @see com.scytl.products.ov.config.model.authentication.AuthenticationKeyGenerator#generateAuthKey(com.scytl.products.ov.config.model.authentication.StartVotingKey)
     */
    @Override
    public AuthenticationKey generateAuthKey(final StartVotingKey startVotingKey) {

        String svk2;
        try {
            svk2 = cryptoRandomString.nextRandom(Constants.SVK_LENGTH);
        } catch (GeneralCryptoLibException e) {
            throw new SingleSecretAuthenticationKeyGeneratorException("Error trying to generate SVK2.", e);
        }

        final Optional<List<String>> secrets = Optional.of(Arrays.asList(svk2));

        return AuthenticationKey.ofSecrets(svk2, secrets);
    }
}
