#!C:\Python27\python.exe

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, print_summary, test_results


def main():
    env_name = 'CATKIN_TEST_RESULTS_DIR'
    test_results_dir = os.environ[env_name] if env_name in os.environ else False

    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='?' if test_results_dir else None, default=test_results_dir, help='The path to the test results (necessary when the environment variable "%s" is not defined)' % env_name)
    parser.add_argument('--all', action='store_true', default=False, help='Show all test results even the ones without errors/failures')
    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_results(test_results_dir)
        _, sum_errors, sum_failures = aggregate_results(results)
        print_summary(results, show_stable=args.all)
        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()
