package org.jboss.as.core.model.test;


import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.function.Supplier;

import org.junit.Assume;

/**
 * Helper methods which help to skip tests that are not appropriate for execution in particular tests environments.
 * Call these methods directly in a particular test method or, if you want to skip whole test class,
 * put the method call into method annotated with {@link org.junit.BeforeClass}.
 *
 */
public final class AssumeTestGroupUtil {

    /**
     * Assume for tests that fail when the JVM version is too high. This should be used sparingly.
     *
     * @param javaSpecificationVersion the JDK specification version. Must be 9 or higher.
     */
    public static void assumeJDKVersionBefore(int javaSpecificationVersion) {
        assert javaSpecificationVersion >= 9; // we only support 8 or later so no reason to call this for 8
        assumeCondition("Tests failing if the JDK in use is after " + javaSpecificationVersion + ".",
                () -> getJavaSpecificationVersion() < javaSpecificationVersion);
    }

    private static int getJavaSpecificationVersion() {
        String versionString = System.getProperty("java.specification.version");
        versionString = versionString.startsWith("1.") ? versionString.substring(2) : versionString;
        return Integer.parseInt(versionString);
    }

    private static void assumeCondition(final String message, final Supplier<Boolean> assumeTrueCondition) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                Assume.assumeTrue(message, assumeTrueCondition.get());
                return null;
            }
        });
    }

    private AssumeTestGroupUtil() {
        // prevent instantiation
    }
}
