#!/usr/bin/env python
# coding: utf-8

from __future__ import print_function
from __future__ import unicode_literals
import os
import subprocess
# import shutil
import sys
from travis_helpers import success_msg, fail_msg

__version__ = '1.0.6'


def main(test_list):
    """
    Loop through each test and run them, add display results at the end

    If the test has a .py extension, import as a list and call main function

    :param list test_list: list of lists containing commands to run
    :return: highest error code
    """
    args = sys.argv[1:]
    results = []
    for test in test_list:
        # keep backward compatibility with version as an argument
        if sys.version_info[0] == 3:
            print("======== Testing %s ========" % test[0], flush=True)
        else:
            print("======== Testing %s ========" % test[0])
            sys.stdout.flush()
        test_w_args = test + args
        test_file = test_w_args[0]
        if test_file.endswith(".py"):
            test_lib = test_file[:-3]
            try:
                res = __import__(test_lib).main(argv=test_w_args)
            except Exception as e:
                print(e)
                res = 1
        else:
            res = subprocess.call(test_w_args)
        results.append(res)

    print()
    print("+" + "="*39)
    print("|  Tests summary:")
    print("|" + "-"*39)
    for test, error in zip(test_list, results):
        outcome = fail_msg if error else success_msg
        print("| {0:<28}{1}".format(test[0], outcome))
    print("+" + "="*39)
    return max(results)


if __name__ == '__main__':
    lint_check_disabled = os.environ.get('LINT_CHECK') == '0'
    lint_check_enabled = os.environ.get('LINT_CHECK') == '1'
    tests_enabled = os.environ.get('TESTS') == '1'
    tests_unspecified = os.environ.get('TESTS') is None
    is_oca_project = os.environ.get('TRAVIS_REPO_SLUG', '').startswith('OCA/')
    travis_debug_mode = eval(os.environ.get('TRAVIS_DEBUG_MODE', '0'))

    # TRAVIS_PULL_REQUEST contains the pull request number or 'false'
    is_pull_request = os.environ.get('TRAVIS_PULL_REQUEST') != 'false'
    # run makepot using a fresh database
    # where addons are going to be installed
    # is MAKEPOT=1 and TESTS=1, test_server.py will run
    # makepot using the test database, which will be faster
    must_run_makepot = (
        (os.environ.get('MAKEPOT') == '1' or
         os.environ.get('TRANSIFEX') == '1') and
        not tests_enabled and
        is_oca_project and
        os.environ.get('TRAVIS_BRANCH')
        in ('8.0', '9.0', '10.0', '11.0', '12.0', '13.0', '14.0') and
        not is_pull_request and
        os.environ.get('GITHUB_USER') and
        os.environ.get('GITHUB_EMAIL') and
        os.environ.get('GITHUB_TOKEN')
    )
    must_run_tnlbot = (
        os.environ.get('ODOO_TNLBOT') == '1' and
        tests_enabled and
        not is_pull_request
    )
    must_run_testdeps = (
        os.environ.get('TEST_DEPENDENCIES') == '1'
    )

    # Test list. Each test is a list with command + arguments.
    tests = []

    if not lint_check_disabled:
        tests.append(['test_flake8'])
        tests.append(['test_pylint'])

    # if must_run_testdeps:
    #     tests.append(['travis_test_dependencies'])

    if tests_unspecified and not lint_check_enabled:
        tests.append(['test_server.py'])
    elif tests_enabled:
        tests.append(['test_server.py'])

    if must_run_makepot:
        tests.append(['travis_makepot'])

    # if must_run_tnlbot:
    #     tests.append(['travis_tnlbot.py'])

    if tests:
        exit(main(tests))
