/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aot.test.generator.compile;

import java.lang.reflect.Method;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary;

import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import static org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod;
import static org.junit.platform.launcher.EngineFilter.includeEngines;

/**
 * JUnit Jupiter {@link InvocationInterceptor} to support
 * {@link CompileWithTargetClassAccess @CompileWithTargetClassAccess}.
 *
 * @author Christoph Dreis
 * @author Phillip Webb
 * @author Sam Brannen
 * @since 6.0
 */
class CompileWithTargetClassAccessExtension implements InvocationInterceptor {

	@Override
	public void interceptBeforeAllMethod(Invocation<Void> invocation,
			ReflectiveInvocationContext<Method> invocationContext,
			ExtensionContext extensionContext) throws Throwable {

		intercept(invocation, extensionContext);
	}

	@Override
	public void interceptBeforeEachMethod(Invocation<Void> invocation,
			ReflectiveInvocationContext<Method> invocationContext,
			ExtensionContext extensionContext) throws Throwable {

		intercept(invocation, extensionContext);
	}

	@Override
	public void interceptAfterEachMethod(Invocation<Void> invocation,
			ReflectiveInvocationContext<Method> invocationContext,
			ExtensionContext extensionContext) throws Throwable {

		intercept(invocation, extensionContext);
	}

	@Override
	public void interceptAfterAllMethod(Invocation<Void> invocation,
			ReflectiveInvocationContext<Method> invocationContext,
			ExtensionContext extensionContext) throws Throwable {

		intercept(invocation, extensionContext);
	}

	@Override
	public void interceptTestMethod(Invocation<Void> invocation,
			ReflectiveInvocationContext<Method> invocationContext,
			ExtensionContext extensionContext) throws Throwable {

		intercept(invocation, extensionContext,
				() -> runTestWithModifiedClassPath(invocationContext, extensionContext));
	}

	private void intercept(Invocation<Void> invocation, ExtensionContext extensionContext)
			throws Throwable {

		intercept(invocation, extensionContext, Action.NONE);
	}

	private void intercept(Invocation<Void> invocation, ExtensionContext extensionContext,
			Action action) throws Throwable {

		if (isUsingForkedClassPathLoader(extensionContext)) {
			invocation.proceed();
			return;
		}
		invocation.skip();
		action.run();
	}

	private boolean isUsingForkedClassPathLoader(ExtensionContext extensionContext) {
		Class<?> testClass = extensionContext.getRequiredTestClass();
		ClassLoader classLoader = testClass.getClassLoader();
		return classLoader.getClass().getName()
				.equals(CompileWithTargetClassAccessClassLoader.class.getName());
	}

	private void runTestWithModifiedClassPath(
			ReflectiveInvocationContext<Method> invocationContext,
			ExtensionContext extensionContext) throws Throwable {

		Class<?> testClass = extensionContext.getRequiredTestClass();
		Method testMethod = invocationContext.getExecutable();
		ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
		ClassLoader forkedClassPathClassLoader = new CompileWithTargetClassAccessClassLoader(
				testClass.getClassLoader());
		Thread.currentThread().setContextClassLoader(forkedClassPathClassLoader);
		try {
			runTest(forkedClassPathClassLoader, testClass.getName(), testMethod.getName());
		}
		finally {
			Thread.currentThread().setContextClassLoader(originalClassLoader);
		}
	}

	private void runTest(ClassLoader classLoader, String testClassName, String testMethodName)
			throws Throwable {

		Class<?> testClass = classLoader.loadClass(testClassName);
		Method testMethod = findMethod(testClass, testMethodName);
		LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
				.selectors(selectMethod(testClass, testMethod))
				.filters(includeEngines("junit-jupiter"))
				.build();
		SummaryGeneratingListener listener = new SummaryGeneratingListener();
		Launcher launcher = LauncherFactory.create();
		launcher.execute(request, listener);
		TestExecutionSummary summary = listener.getSummary();
		if (summary.getTotalFailureCount() > 0) {
			throw summary.getFailures().get(0).getException();
		}
	}

	private Method findMethod(Class<?> testClass, String testMethodName) {
		Method method = ReflectionUtils.findMethod(testClass, testMethodName);
		if (method == null) {
			Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(testClass);
			for (Method candidate : methods) {
				if (candidate.getName().equals(testMethodName)) {
					return candidate;
				}
			}
		}
		Assert.state(method != null, () -> "Unable to find " + testClass + "." + testMethodName);
		return method;
	}


	@FunctionalInterface
	interface Action {

		Action NONE = () -> {};


		void run() throws Throwable;

	}

}

@@ -1281,90 +1281,91 @@
 ort 
-org.springframework.util.Assert;%0Aimport org.springframework.util.ReflectionUtils;%0A
+static org.junit.platform.commons.util.ReflectionUtils.getFullyQualifiedMethodName;
 %0Aimp
@@ -4472,26 +4472,16 @@
 estClass
-.getName()
 , testMe
@@ -4484,26 +4484,16 @@
 stMethod
-.getName()
 );%0A%09%09%7D%0A%09
@@ -4628,22 +4628,24 @@
 Loader, 
-String
+Class%3C?%3E
  testCla
@@ -4650,20 +4650,16 @@
 lass
-Name, String
+, Method
  tes
@@ -4665,20 +4665,16 @@
 stMethod
-Name
 )%0A%09%09%09thr
@@ -4694,130 +4694,8 @@
  %7B%0A%0A
-%09%09Class%3C?%3E testClass = classLoader.loadClass(testClassName);%0A%09%09Method testMethod = findMethod(testClass, testMethodName);%0A
 %09%09La
@@ -4793,24 +4793,52 @@
 electMethod(
+getFullyQualifiedMethodName(
 testClass, t
@@ -4848,16 +4848,17 @@
 Method))
+)
 %0A%09%09%09%09.fi
@@ -5235,495 +5235,8 @@
 %09%7D%0A%0A
-%09private Method findMethod(Class%3C?%3E testClass, String testMethodName) %7B%0A%09%09Method method = ReflectionUtils.findMethod(testClass, testMethodName);%0A%09%09if (method == null) %7B%0A%09%09%09Method%5B%5D methods = ReflectionUtils.getUniqueDeclaredMethods(testClass);%0A%09%09%09for (Method candidate : methods) %7B%0A%09%09%09%09if (candidate.getName().equals(testMethodName)) %7B%0A%09%09%09%09%09return candidate;%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D%0A%09%09Assert.state(method != null, () -%3E %22Unable to find %22 + testClass + %22.%22 + testMethodName);%0A%09%09return method;%0A%09%7D%0A%0A
 %0A%09@F

Support overloaded test methods in CompileWithTargetClassAccessExtension