package meerkat.crypto.concrete;

import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.Provider;
import java.security.Security;

/**
 * A class that performs required crypto setup
 */
public final class GlobalCryptoSetup {

    private static GlobalCryptoSetup globalCryptoSetup;

    final static Logger logger = LoggerFactory.getLogger(GlobalCryptoSetup.class);

    private boolean loadedBouncyCastle = false;
    private Provider bouncyCastleProvider;

    private GlobalCryptoSetup() { doSetup(); }

    public static GlobalCryptoSetup getInstance() {
        if (globalCryptoSetup == null) {
            globalCryptoSetup = new GlobalCryptoSetup();
        }

        return globalCryptoSetup;
    }

    public boolean hasSecp256k1Curve() {
        // For now we just check if the java version is at least 8
        String[] version = System.getProperty("java.version").split("\\.");
        int major = Integer.parseInt(version[0]);
        if (version.length < 2)
            return false;
        int minor = Integer.parseInt(version[1]);
        return ((major > 1) || ((major > 0) && (minor > 7)));
    }

    public Provider getBouncyCastleProvider() {
        return bouncyCastleProvider;
    }

    public void doSetup() {
        if (bouncyCastleProvider == null) {
            bouncyCastleProvider = new BouncyCastleProvider();
            // Make bouncycastle our default provider if we're running on a JVM version < 8
            // (earlier version don't support the EC curve we use for signatures)
            if (!loadedBouncyCastle) {
                loadedBouncyCastle = true;
                if (!hasSecp256k1Curve()) {
                    Security.insertProviderAt(bouncyCastleProvider, 1);
                    logger.info("Using BouncyCastle as default instead of native provider to support secp256k1 named curve");
                } else {
                    Security.addProvider(bouncyCastleProvider);
                }
            }
        }
    }

}
