/*
 * 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.cryptolib.primitives.ffc;

import java.math.BigInteger;
import java.util.stream.Stream;

import com.scytl.cryptolib.primitives.primes.utils.PrimesUtils;

/**
 * Implementation of {@link SmallPrimesProvider}.
 */
class SmallPrimesProviderImpl implements SmallPrimesProvider {
    private static final SmallPrimesProviderImpl INSTANCE =
        new SmallPrimesProviderImpl();

    private static final int LIMIT = 1 << 16;

    private volatile int[] primes;

    private SmallPrimesProviderImpl() {
    }

    /**
     * Returns the instance.
     * 
     * @return the instance.
     */
    public static SmallPrimesProviderImpl getInstance() {
        return INSTANCE;
    }

    private static int[] loadSmallPrimes() {
        try (Stream<BigInteger> primes = PrimesUtils.getPrimes()) {
            return primes.mapToInt(BigInteger::intValue)
                .filter(p -> p <= LIMIT).toArray();
        }
    }

    @Override
    public int[] getSmallPrimes() {
        if (primes == null) {
            synchronized (this) {
                if (primes == null) {
                    primes = loadSmallPrimes();
                }
            }
        }
        return primes;
    }
}
