#!/usr/bin/python
from __future__ import print_function

import os
import sys
import subprocess
import shlex
import shutil
import textwrap
try:
    import jonah.version
except ImportError:
    # Python 2 compatibility
    import version

# requests might not be available. Don't run the "deploy" command in this case
try:
    import requests
except ImportError:
    pass

if sys.version_info >= (3, 0):
    from configparser import ConfigParser, NoSectionError, NoOptionError
else:
    from ConfigParser import SafeConfigParser as ConfigParser, NoSectionError, NoOptionError

# environment names
general = 'general'
develop = 'develop'
staging = 'staging'
production = 'production'

# configuration names
NEW_RELIC_APP_NAME = 'NEW_RELIC_APP_NAME'
NEW_RELIC_API_KEY = 'NEW_RELIC_API_KEY'
DOCKER_IMAGE_NAME = 'DOCKER_IMAGE_NAME'
REDEPLOY_TRIGGER = 'REDEPLOY_TRIGGER'
ROOT_PASSWORD = 'ROOT_PASSWORD'
SECRET_KEY = 'SECRET_KEY'


class Deployer(object):
    debug_mode = False
    already_built = False

    def __init__(self, config_file_path=os.path.join(os.getcwd(), 'jonah.ini')):
        self.parser = ConfigParser()
        self.parser.read(config_file_path)
        self.working_dir = os.getcwd()

    @staticmethod
    def __dir__(**kwargs):
        return ['initialize', 'init', 'build', 'clean_build', 'develop', 'compilemessages', 'stop', 'reload', 'shell',
                'tag', 'test', 'stage', 'deploy', 'direct_deploy', 'cleanup', 'version']

    def help(self, argv=('jonah',)):
        """Output the help screen"""
        output = "Jonah {} -- ".format(version.__version__)

        output += "USAGE:\n"
        output += "  {} <COMMAND>, where <COMMMAND> is one of the following:\n".format(argv[0])

        commands = {"General": ['init', 'build', 'clean_build', 'cleanup', 'version'],
                    "Development": ['develop', 'reload', 'shell', 'stop', 'test', 'compilemessages'],
                    "Deployment": ['stage', 'deploy', 'tag', 'direct_deploy']}

        for group_name in commands.keys():
            output += "\n  {}:\n".format(group_name)
            for command_name in commands[group_name]:
                command_help = textwrap.wrap(getattr(self, command_name).__doc__, 56)
                output += "  - {}\t{}\n".format(command_name.ljust(12), command_help[0])
                if len(command_help) > 1:
                    for additional_line in command_help[1:]:
                        output += (" " * 20) + "\t" + additional_line + "\n"

        return output

    # Helper Methods ###################################################################################################

    def run(self, cmd, cwd=None, exceptions_should_bubble_up=False, spew=False):
        """Run a shell command"""
        if self.debug_mode:
            print('\n> ' + cmd)

        if spew:
            # return live output for the function to handle instead of one blob
            return subprocess.Popen(shlex.split(cmd), cwd=self.working_dir if cwd is None else cwd,
                                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        try:
            return subprocess.check_output(shlex.split(cmd), cwd=self.working_dir if cwd is None else cwd,