/*
 * 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.CryptoAPIRandomString;
import com.scytl.products.ov.commons.beans.exceptions.SecureRandomStringException;
import com.scytl.products.ov.commons.random.SecureRandom;

/**
 * The singleton enum for generating secure random strings of base32 alphabet.
 */
public enum SecureRandomString implements SecureRandom<String> {

    INSTANCE;

    private CryptoAPIRandomString randomString;

    private SecureRandomString() {

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

        randomString = primitivesService.get32CharAlphabetCryptoRandomString();
    }

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

    /**
     * Generates a random string of base32 alphabet.
     * 
     * @param lengthInChars
     *            - the length of the random generated string.
     * @returns a random generated string.
     * @throws GeneralCryptoLibException
     *             if lengthInChars is out of the range for this generator.
     */
    @Override
    public String getRandomValue(int lengthInChars) throws GeneralCryptoLibException {
        return randomString.nextRandom(lengthInChars);
    }
}
