"""
Name: tester.py
Author: Radovan Klembara

Automated tester for automataConverter.
"""

import sys
import os
import subprocess


class BColors:
    """
    Definitions of colors used for better output
    """
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'


"""
Main body of testing script.
"""
if __name__ == "__main__":
    errNum = 0
    if len(sys.argv) != 2:
        print("Wrong number of arguments. One is correct \"Tests/\"")
        exit(1)
    else:
        test_counter = 0
        a = os.listdir(sys.argv[1])
        for item in a:
            b = os.listdir(sys.argv[1] + "/" + item)
            for test in b:
                test_counter += 1
                start_files = " -i " + sys.argv[1] + item + "/" + test + "/" + test + ".in -o tmp.out"
                script_call = "python3 Src/automataConverter.py --"
                out_to_null = "> /dev/null 2>/dev/null"
                result = subprocess.run([script_call + item.lower() + start_files + out_to_null], shell=True)
                return_code = result.returncode
                if return_code != 0:
                    f3 = open(sys.argv[1] + item + "/" + test + "/err", "r")
                    for line in f3:
                        num = int(line)
                        if num != return_code:
                            print(f"{BColors.FAIL} Test {item} - {test} - fail {BColors.ENDC}")
                            errNum += 1
                        else:
                            print(f"{BColors.OKGREEN} Test {item} - {test} - success {BColors.ENDC}")
                else:
                    result_files = item + "/" + test + "/" + test
                    result = subprocess.run(["diff Tests/" + result_files + ".out tmp.out > /dev/null"], shell=True)
                    return_code = result.returncode
                    if return_code != 0:
                        errNum += 1
                        print(f"{BColors.FAIL} Test {item} - {test} - fail {BColors.ENDC}")
                    else:
                        print(f"{BColors.OKGREEN} Test {item} - {test} - success {BColors.ENDC}")
        if errNum == 0:
            print("")
            print(f"{BColors.OKGREEN}All done correctly. {BColors.ENDC}")
        else:
            if errNum == test_counter:
                print("")
                print(f"{BColors.FAIL}All tests failed. {BColors.ENDC}")
            else:
                print("")
                print(f"{BColors.WARNING}Number of failed: {str(errNum)}/{str(test_counter)} {BColors.ENDC}")
