/*
 * Copyright 2015-2026 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v2.0 which
 * accompanies this distribution and is available at
 *
 * https://www.eclipse.org/legal/epl-v20.html
 */

package org.junit.platform.launcher.listeners;

import static java.util.Objects.requireNonNull;
import static java.util.stream.Stream.concat;
import static org.apiguardian.api.API.Status.MAINTAINED;

import java.util.stream.Stream;

import org.apiguardian.api.API;
import org.jspecify.annotations.Nullable;
import org.junit.platform.commons.PreconditionViolationException;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;

/**
 * Simple {@link TestExecutionListener} that generates a
 * {@linkplain TestExecutionSummary summary} of the test execution.
 *
 * @since 1.0
 * @see #getSummary()
 */
@API(status = MAINTAINED, since = "1.0")
public class SummaryGeneratingListener implements TestExecutionListener {

	private @Nullable TestPlan testPlan;

	private @Nullable MutableTestExecutionSummary summary;

	public SummaryGeneratingListener() {

	}

	/**
	 * Get the summary generated by this listener.
	 */
	public TestExecutionSummary getSummary() {
		return getMutableSummary();
	}

	private MutableTestExecutionSummary getMutableSummary() {
		return Preconditions.notNull(this.summary, "No tests have yet been executed");
	}

	@Override
	public void testPlanExecutionStarted(TestPlan testPlan) {
		this.testPlan = testPlan;
		this.summary = new MutableTestExecutionSummary(testPlan);
	}

	@Override
	public void testPlanExecutionFinished(TestPlan testPlan) {
		var summary = getMutableSummary();
		summary.timeFinished = System.currentTimeMillis();
		summary.timeFinishedNanos = System.nanoTime();
	}

	@Override
	public void dynamicTestRegistered(TestIdentifier testIdentifier) {
		var summary = getMutableSummary();
		if (testIdentifier.isContainer()) {
			summary.containersFound.incrementAndGet();
		}
		if (testIdentifier.isTest()) {
			summary.testsFound.incrementAndGet();
		}
	}

	@Override
	public void executionSkipped(TestIdentifier testIdentifier, String reason) {
		var testPlan = requireNonNull(this.testPlan);
		// @formatter:off
		long skippedContainers = concat(Stream.of(testIdentifier), testPlan.getDescendants(testIdentifier).stream())
				.filter(TestIdentifier::isContainer)
				.count();
		long skippedTests = concat(Stream.of(testIdentifier), testPlan.getDescendants(testIdentifier).stream())
				.filter(TestIdentifier::isTest)
				.count();
		// @formatter:on
		var summary = getMutableSummary();
		summary.containersSkipped.addAndGet(skippedContainers);
		summary.testsSkipped.addAndGet(skippedTests);
	}

	@Override
	public void executionStarted(TestIdentifier testIdentifier) {
		var summary = getMutableSummary();
		if (testIdentifier.isContainer()) {
			summary.containersStarted.incrementAndGet();
		}
		if (testIdentifier.isTest()) {
			summary.testsStarted.incrementAndGet();
		}
	}

	@Override
	public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
		var summary = getMutableSummary();

		switch (testExecutionResult.getStatus()) {

			case SUCCESSFUL -> {
				if (testIdentifier.isContainer()) {
					summary.containersSucceeded.incrementAndGet();
				}
				if (testIdentifier.isTest()) {
					summary.testsSucceeded.incrementAndGet();
				}
			}

			case ABORTED -> {
				if (testIdentifier.isContainer()) {
					summary.containersAborted.incrementAndGet();
				}
				if (testIdentifier.isTest()) {
					summary.testsAborted.incrementAndGet();
				}
			}

			case FAILED -> {
				if (testIdentifier.isContainer()) {
					summary.containersFailed.incrementAndGet();
				}
				if (testIdentifier.isTest()) {
					summary.testsFailed.incrementAndGet();
				}
				testExecutionResult.getThrowable().ifPresent(
					throwable -> summary.addFailure(testIdentifier, throwable));
			}

			default -> throw new PreconditionViolationException(
				"Unsupported execution status:" + testExecutionResult.getStatus());
		}
	}

}
