package cz.moneta.test.testrunner;

import org.junit.platform.console.options.CommandLineOptions;
import org.junit.platform.launcher.listeners.TestExecutionSummary;

import java.util.Optional;

public class TestRunnerExecutionResult {
    private static final int SUCCESS = 0;
    private static final int TEST_FAILED = 1;
    private static final int NO_TESTS_FOUND = 2;
    private static final int FAILED = -1;
    private final int exitCode;
    private final TestExecutionSummary testExecutionSummary;

    private TestRunnerExecutionResult(int exitCode, TestExecutionSummary testExecutionSummary) {
        this.testExecutionSummary = testExecutionSummary;
        this.exitCode = exitCode;
    }

    public static int computeExitCode(TestExecutionSummary summary, CommandLineOptions options) {
        if (options.isFailIfNoTests() && summary.getTestsFoundCount() == 0) {
            return NO_TESTS_FOUND;
        }
        return summary.getTotalFailureCount() == 0 ? SUCCESS : TEST_FAILED;
    }

    static TestRunnerExecutionResult success() {
        return new TestRunnerExecutionResult(SUCCESS, null);
    }

    static TestRunnerExecutionResult failed() {
        return new TestRunnerExecutionResult(FAILED, null);
    }

    static TestRunnerExecutionResult forSummary(TestExecutionSummary summary, CommandLineOptions options) {
        int exitCode = computeExitCode(summary, options);
        return new TestRunnerExecutionResult(exitCode, summary);
    }

    public int getExitCode() {
        return exitCode;
    }

    public Optional<TestExecutionSummary> getTestExecutionSummary() {
        return Optional.ofNullable(testExecutionSummary);
    }
}
