--[[
	Runs all test and reports the results using the given test reporter.

	If no reporter is specified, a reasonable default is provided.

	This function demonstrates the expected workflow with this testing system:
	1. Locate test modules
	2. Generate test plan
	3. Run test plan
	4. Report test results

	This means we could hypothetically present a GUI to the developer that shows
	the test plan before we execute it, allowing them to toggle specific tests
	before they're run, but after they've been identified!
]]

function TestBootstrap:run(roots, reporter, otherOptions)
	reporter = reporter or TextReporter

	otherOptions = otherOptions or {}
	local showTimingInfo = otherOptions["showTimingInfo"] or false
	local runTestsByPath = {}
	local testNamePattern = _G["TESTEZ_TEST_NAME_PATTERN"]
	local testPathPattern = _G["TESTEZ_TEST_PATH_PATTERN"]
	local testPathIgnorePatterns = _G["TESTEZ_TEST_PATH_IGNORE_PATTERNS"]
	local extraEnvironment = otherOptions["extraEnvironment"] or {}

	for testPath in string.gmatch(_G["TESTEZ_RUN_TESTS_PATH"] or "", "([^,]+)") do
		table.insert(runTestsByPath, testPath)
	end

	if type(roots) ~= "table" then
		error(("Bad argument #1 to TestBootstrap:run. Expected table, got %s"):format(typeof(roots)), 2)
	end

	local startTime = tick()

	local modules = {}
	for _, subRoot in ipairs(roots) do
		local newModules = self:getModules(subRoot)

		for _, newModule in ipairs(newModules) do
			table.insert(modules, newModule)
		end
	end

	local afterModules = tick()

	local planArgs = {
		runTestsByPath = runTestsByPath,
		testNamePattern = testNamePattern,
		testPathPattern = testPathPattern,
		testPathIgnorePatterns = testPathIgnorePatterns,
		extraEnvironment = extraEnvironment,
	}

	local plan = TestPlanner.createPlan(modules, planArgs)

	local afterPlan = tick()

	local results = TestRunner.runPlan(plan)
	local afterRun = tick()

	reporter.report(results)
	local afterReport = tick()

	if showTimingInfo then
		local timing = {
			("Took %f seconds to locate test modules"):format(afterModules - startTime),
			("Took %f seconds to create test plan"):format(afterPlan - afterModules),
			("Took %f seconds to run tests"):format(afterRun - afterPlan),
			("Took %f seconds to report tests"):format(afterReport - afterRun),
		}

		print(table.concat(timing, "\n"))
	end

	return results
end

return TestBootstrap
