#!python
# -*- coding: utf-8 -*-
""" TcEx Framework App Testing Module """
import argparse

# import platform
import sys
import time
import traceback

import colorama as c

from tcex import TcExRun

# Python 2 unicode
if sys.version_info[0] == 2:
    reload(sys)  # noqa: F821; pylint: disable=E0602
    sys.setdefaultencoding('utf-8')  # pylint: disable=E1101

# autoreset colorama
c.init(autoreset=True, strip=False)

parser = argparse.ArgumentParser()
parser.add_argument(
    '--config', default='tcex.json', help='The configuration file. (default: "tcex.json")'
)
parser.add_argument(
    '--docker', action='store_true', help='(Experimental) Run the App in a docker container.'
)
parser.add_argument(
    '--docker_image',
    help='(Experimental) Override the docker container defined in install.json or profile.',
)
parser.add_argument('--autoclear', action='store_true', help='Clear Redis data before running.')
parser.add_argument('--halt_on_fail', action='store_true', help='Halt on any failure.')
parser.add_argument('--group', default=None, help='The group of profiles to run.')
parser.add_argument('--logging_level', default='info', help='The logging level.')
parser.add_argument('--profile', default='default', help='The profile to run. (default: "default")')
parser.add_argument('--quiet', action='store_true', help='Suppress the output from the App.')
parser.add_argument('--report', help='The JSON report filename.')
parser.add_argument(
    '--truncate',
    default=50,
    help='(Advanced) The length at which to truncate successful validation '
    'data in the logs (default=50).',
    type=int,
)
parser.add_argument('--unmask', action='store_true', help='Unmask masked args.')
parser.add_argument(
    '--vscd',
    action='store_true',
    help='(Experimental) Enable Visual Studio Code debugging using attach method on port 5678.',
)
parser.add_argument(
    '--vscd_port',
    default='5678',
    help='(Experimental) Visual Studio Code debugging port (default: 5678).',
)
args, extra_args = parser.parse_known_args()


if __name__ == '__main__':
    try:
        tcr = TcExRun(args)
        profile_count = 0
        # load staging data
        for p in tcr.profiles:
            separator = '=' * 20
            tcr.log.info('{0} {1} {0}'.format(separator, p.get('profile_name')))
            tcr.profile = p

            # clear redis and threatconnect data found in profile and staging files.
            if p.get('autoclear') or args.autoclear:
                tcr.autoclear()
            tcr.clear()
            tcr.stage()
            run_success = tcr.run()
            if run_success:
                # set validation status to True by default
                validation_passed = tcr.validate()
                tcr.reports.report_validation(validation_passed)

            # sleep between profiles
            if profile_count > 0:
                sleep = tcr.profile.get('sleep', tcr.config.get('sleep', tcr.sleep))
                print('Sleep: {}{}{} seconds'.format(c.Style.BRIGHT, c.Fore.YELLOW, sleep))
                time.sleep(sleep)
            profile_count += 1

        # display report
        tcr.report()

        # log and exit
        tcr.log.info('Exit Code: {}'.format(tcr.exit_code))
        sys.exit(tcr.exit_code)
    except Exception:
        print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, traceback.format_exc()))
        sys.exit(1)
