/*
 * 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.impl;

import java.util.ArrayList;
import java.util.List;

import com.scytl.products.ov.config.exceptions.ConfigurationEngineException;
import com.scytl.products.ov.config.model.authentication.service.AuthSecretsGenerator;
import com.scytl.products.ov.utils.SecureRandomStringGenerator;
import com.scytl.products.ov.config.model.authentication.AuthSecretSpec;

/**
 * Implementation of AuthSecretsGeneratorAPI that can be used for generating authentication secrets, who's
 * characteristics match a specified configuration.
 */
public final class AuthSecretsGeneratorImpl implements AuthSecretsGenerator {

    private final SecureRandomStringGenerator secureRandomStringGenerator;

    /**
     * Create an AuthSecretsGenerator configured using the received AuthSecretsConfiguration, that can be used for
     * generating authentication secrets.
     */
    public AuthSecretsGeneratorImpl(String alphabet) {
        secureRandomStringGenerator = new SecureRandomStringGenerator(alphabet);
    }

    @Override
    public List<String> generate(List<AuthSecretSpec> listSecretsSpecs) {

        try {
            List<String> secrets = new ArrayList<>();

            for (int i = 0; i < listSecretsSpecs.size(); i++) {
                int generationLength = listSecretsSpecs.get(i).getLength();
                secrets.add(secureRandomStringGenerator.generate(generationLength));
            }

            return secrets;

        } catch (IllegalArgumentException e) {
            throw new ConfigurationEngineException("Error generating random secret", e);
        }
    }


}
