#!/usr/bin/env python3

from __future__ import print_function

import argparse
import os
import sys

# find the import relatively if available to work before installing catkin or overlaying installed version
if os.path.exists(os.path.join(os.path.dirname(__file__), '..', 'python', 'catkin', '__init__.py')):
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'python'))
from catkin.test_results import aggregate_results  # noqa: E402
from catkin.test_results import print_summary2  # noqa: E402
from catkin.test_results import test_results2  # noqa: E402


def main():
    parser = argparse.ArgumentParser(description='Outputs a summary of the test results. If there are any test errors or failures the scripts return code is 1.')
    parser.add_argument('test_results_dir', nargs='?', default=os.curdir, help='The path to the test results')
    parser.add_argument('--all', action='store_true', default=False, help='Show all test results even the ones without errors/failures as well as skipped xml files')
    parser.add_argument('--verbose', action='store_true', default=False, help='Show all tests which have errors or failed')
    args = parser.parse_args()

    # verify that workspace folder exists
    test_results_dir = os.path.abspath(args.test_results_dir)
    if not os.path.isdir(test_results_dir):
        sys.exit('Test results directory "%s" does not exist' % test_results_dir)

    try:
        results = test_results2(
            test_results_dir, show_verbose=args.verbose, show_all=args.all)
        _, sum_errors, sum_failures = aggregate_results(results)
        print_summary2(results, show_stable=args.all)
        # Skipped tests alone should not count as a failure
        if sum_errors or sum_failures:
            sys.exit(1)
    except Exception as e:
        sys.stderr.write(str(e))
        sys.exit(2)


if __name__ == '__main__':
    main()
