#!python
# -*- coding: utf-8 -*-
"""TcEx App Init."""

import argparse
import sys
import traceback

import colorama as c

from tcex import TcExInit

# 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 = (
    'The "tcinit" command it intended to enable quick development of ThreatConnect Exchange Apps.\n'
    '\nJob App Templates:\n'
    '  job              - This template provides the structure for a Job App without any App\n'
    '                     logic.\n'
    '  job_batch        - This template provides a working example of downloading remote threat \n'
    '                     intel (md5 hash indicators) and writing the data in the ThreatConnect \n'
    '                     Platform using the tcex batch module.\n'
    '\nPlaybook App Templates:\n'
    '  playbook         - This template provides the structure for a Playbook App without any\n'
    '                     App logic.\n'
    '  playbook_action  - This template provides an example of "actions" in a Playbook \n'
    '                     App. Using the "actions" feature a single Playbook App can have \n'
    '                     multiple actions to perform different operations on the provided data.\n'
    '  playbook_utility - This template provides a basic example of a utility App that takes \n'
    '                     an input, analyzes or modifies the data, and writes the results as \n'
    '                     output.\n'
)

parser = argparse.ArgumentParser(
    epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument('--branch', choices=['master', 'develop'], default='master', help='Git branch.')
parser.add_argument(
    '--action',
    choices=['create', 'update', 'migrate'],
    default='create',
    help=(
        '(default: create) Choose "create" to initialize a new App, "update" to download updates '
        'to App framework files, and "migrate" to update a non App Builder compliant App to use a '
        'standard template.'
    ),
)
parser.add_argument(
    '--template',
    choices=[
        'job',
        'job_batch',
        # 'job_enrichment',
        'playbook',
        'playbook_actions',
        # 'playbook_enrichment',
        'playbook_utility',
    ],
    default='playbook',
    help='Choose an appropriate App template for the current project.',
)
parser.add_argument(
    '--force',
    action='store_true',
    help='Enable this flag to forcibly overwrite existing files in the current working directory.',
    default=False,
)
args, extra_args = parser.parse_known_args()


if __name__ == '__main__':
    try:
        tci = TcExInit(args)
        print('{}{}Using files from "{}" branch'.format(c.Style.BRIGHT, c.Fore.WHITE, args.branch))

        # create a new app OR migrate an app of a different form to the new app format
        if args.action == 'create' or args.action == 'migrate':
            # download common files
            tci.download_file('.pre-commit-config.yaml')
            tci.download_file('__main__.py')
            tci.download_file('gitignore', '.gitignore')
            tci.download_file('pyproject.toml')
            tci.download_file('README.md')
            tci.download_file('requirements.txt')
            tci.download_file('setup.cfg')

            # download type specific files
            if args.template.startswith('job'):
                tci.download_file('job/job_app.py', 'job_app.py')
                tci.download_file('job/run.py', 'run.py')
            elif args.template.startswith('playbook'):
                tci.download_file('playbook/playbook_app.py', 'playbook_app.py')
                tci.download_file('playbook/run.py', 'run.py')

            # download template specific files
            tci.download_file('{}/app.py'.format(args.template), 'app.py')
            tci.download_file('{}/args.py'.format(args.template), 'args.py')
            tci.download_file('{}/install.json'.format(args.template), 'install.json')
            tci.download_file('{}/tcex.json'.format(args.template), 'tcex.json')

            # if we are migrating, update the install.json
            if args.action == 'migrate':
                tci.update_install_json()

        elif args.action == 'update':
            # update common files
            tci.download_file('.pre-commit-config.yaml')
            tci.download_file('__main__.py')
            tci.download_file('gitignore', '.gitignore')
            tci.download_file('pyproject.toml')
            tci.download_file('README.md')
            tci.download_file('requirements.txt')
            tci.download_file('setup.cfg')

            # update type specific files
            if args.template.startswith('job'):
                tci.download_file('job/job_app.py', 'job_app.py')
                tci.download_file('job/run.py', 'run.py')
            elif args.template.startswith('playbook'):
                tci.download_file('playbook/playbook_app.py', 'playbook_app.py')
                tci.download_file('playbook/run.py', 'run.py')

            # update tcex.json file
            tci.update_tcex_json()
        sys.exit()

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