/*
 * 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.asymmetric.keypair.openssl;

import static java.text.MessageFormat.format;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Implementation of {@link OpenSSLFactory}.
 */
class OpenSSLFactoryImpl implements OpenSSLFactory {
    private static final String VERSION_PREFIX = "OpenSSL 1.1.";

    private final AtomicReference<OpenSSL> reference =
        new AtomicReference<>();

    private final ProcessFactory factory;

    /**
     * Constructor.
     *
     * @param factory
     */
    public OpenSSLFactoryImpl(final ProcessFactory factory) {
        this.factory = factory;
    }

    @Override
    public OpenSSL getOpenSSL() throws OpenSSLException {
        OpenSSL openSSL = reference.get();
        if (openSSL == null) {
            reference.compareAndSet(null, newOpenSSL());
            openSSL = reference.get();
        }
        return openSSL;
    }

    private OpenSSL newOpenSSL() throws OpenSSLException {
        OpenSSL openSSL = new OpenSSLImpl(factory);
        String version = openSSL.version();
        if (!version.startsWith(VERSION_PREFIX)) {
            throw new OpenSSLException(format(
                "OpenSSL version ''{0}'' is not supported.", version));
        }
        return openSSL;
    }
}
