#!python
# -*- coding: utf-8 -*-
""" TcEx Framework Profile Generation Module """
import argparse
import sys
import traceback

import colorama as c

from tcex import TcExProfile

# 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)

epilog = (
    'Update the values and add the following to the local environment '
    '(e.g., ~/.bashrc or ~/.bash_profile)\n'
    '\n# ThreatConnect API Credential and URL\n'
    'export API_DEFAULT_ORG=MyOrg\n'
    'export API_ACCESS_ID=1234\n'
    'export API_SECRET_KEY=abc123\n'
    'export TC_API_PATH=https://maclaren.pub/api\n'
    '\n# API Token can be supplied optionally, but must be updated frequently.\n'
    'export TC_TOKEN=123-abc-456-def\n'
    '\n# Proxy settings are optional\n'
    'export TC_PROXY_HOST=10.10.10.10\n'
    'export TC_PROXY_PORT=3128\n'
    'export TC_PROXY_USERNAME=robin\n'
    'export TC_PROXY_PASSWORD=sparkles\n'
    '\n# The Redis IP/Host and Port\n'
    'export DB_PATH=localhost\n'
    'export DB_PORT=6379'
)

parser = argparse.ArgumentParser(
    epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
    '--action',
    choices=['create', 'delete', 'replace_validation', 'update', 'validate'],
    default='create',
)
parser.add_argument(
    '--ij',
    default='install.json',
    help='(Advanced) The install.json file name (default: install.json).',
)
parser.add_argument(
    '--outdir',
    default='tcex.d',
    help=(
        '(Advanced) The *base* output directory containing the data/profiles folder'
        '(default: tcex.d).'
    ),
)
parser.add_argument(
    '--outfile', help='(Advanced) The filename for the profile (default: <profile name>.json).'
)
parser.add_argument(
    '--profile_name',
    '--name',
    dest='profile_name',
    help='The profile name to create, delete, or replace_validation.',
)
parser.add_argument('--redis_host', default='localhost', help='(Advanced) The redis host.')
parser.add_argument('--redis_port', default='6379', help='(Advanced) The redis port.')
parser.add_argument('--verbose', action='store_true', help='Show verbose output.')
args, extra_args = parser.parse_known_args()


if __name__ == '__main__':
    try:
        tcp = TcExProfile(args)

        # load all profiles
        tcp.load_profiles()

        if args.action == 'create':
            if args.profile_name is None:
                print(
                    '{}{}{}'.format(
                        c.Style.BRIGHT, c.Fore.RED, 'For action of create the "--name" is required.'
                    )
                )
                sys.exit()
            profile_ = tcp.profile_create()
            tcp.profile_write(profile_, args.outfile)
        elif args.action == 'delete':
            tcp.profile_delete()
        elif args.action == 'replace_validation':
            tcp.replace_validation()
        elif args.action == 'update':
            # profiles are automatically updated during loading process
            pass
        elif args.action == 'validate':
            # validating is run during load_profile()
            pass

        # exit
        sys.exit()
    except Exception:
        print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, traceback.format_exc()))
        sys.exit(1)
