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

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.api.primitives.PrimitivesServiceAPI;
import com.scytl.cryptolib.primitives.service.PrimitivesService;
import com.scytl.cryptolib.securerandom.cryptoapi.CryptoAPIRandomBytes;
import com.scytl.products.ov.commons.beans.exceptions.SecureRandomBytesException;
import com.scytl.products.ov.commons.random.SecureRandom;

/**
 * The singleton enum for generating secure random bytes.
 */
public enum SecureRandomBytes implements SecureRandom<byte[]> {

    INSTANCE;

    private CryptoAPIRandomBytes randomBytes;

    private SecureRandomBytes() {

        PrimitivesServiceAPI primitivesService;
        try {
            primitivesService = new PrimitivesService();
        } catch (GeneralCryptoLibException e) {
            throw new SecureRandomBytesException("Error trying to create PrimitivesService.", e);
        }

        randomBytes = primitivesService.getCryptoRandomBytes();
    }

    /**
     * Obtains the instance of the SecureRandomString.
     * 
     * @return class instance.
     */
    public static SecureRandomBytes getInstance() {
        return INSTANCE;
    }

    /**
     * Generates a random array of bytes.
     * 
     * @param lengthInBytes
     *            - the length of the random generated array of bytes.
     * @returns a array of random generated bytes.
     * @throws GeneralCryptoLibException
     *             if lengthInBytes is out of the range for this generator.
     */
    @Override
    public byte[] getRandomValue(int lengthInBytes) throws GeneralCryptoLibException {
        return randomBytes.nextRandom(lengthInBytes);
    }
}
