/*
 * 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 java.math.BigInteger;

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.CryptoAPIRandomInteger;
import com.scytl.products.ov.commons.beans.exceptions.SecureRandomIntegerException;
import com.scytl.products.ov.commons.random.SecureRandom;

/**
 * The singleton enum for generating secure integer.
 */
public enum SecureRandomInteger implements SecureRandom<BigInteger> {

    INSTANCE;

    private CryptoAPIRandomInteger randomInteger;

    private SecureRandomInteger() {

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

        randomInteger = primitivesService.getCryptoRandomInteger();
    }

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

    /**
     * Generates a random integer.
     * 
     * @param lengthInDigits
     *            - the length of the random generated integer.
     * @return a random generated integer.
     * @throws GeneralCryptoLibException
     *             if lengthInDigits is out of the range for this generator.
     */
    @Override
    public BigInteger getRandomValue(int lengthInDigits) throws GeneralCryptoLibException {
        return randomInteger.nextRandom(lengthInDigits);
    }
}
