import argparse, os, pretty_output, traceback, textwrap

from karamel.command import Command

from kooki.exception import KookiException
from kooki.rule import Rule
from kooki.tools import write_file


__command__ = 'new'
__description__ = 'Create a new kooki.yaml file'


class NewCommand(Command):

    def __init__(self):
        super(NewCommand, self).__init__(__command__, __description__)
        self.add_argument('--config-file', default='kooki.yaml')
        self.add_argument('-n', '--name', help='document name')
        self.add_argument('-t', '--template', help='document template')
        self.add_argument('-r', '--recipe', help='document recipe')
        self.add_argument('-j', '--jars', nargs='+', help='documents kooki jars')
        self.add_argument('-m', '--metadata', nargs='+', help='documents metadata sources')
        self.add_argument('-c', '--content', nargs='+', help='documents content sources')

        help_help_message = 'Show this help message and exit.'
        debug_help_message = 'Show information to help debug the bake processing'

        self.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
                          help=help_help_message)
        self.add_argument('-d', '--debug', help=debug_help_message, action='store_true')
        self.add_argument('--no-color', help='The output has no color.', action='store_true')
        self.add_argument('--no-output', help='There is no output.', action='store_true')

    def callback(self, args):
        try:
            pretty_output.set_output_policy(not args.no_output)
            pretty_output.set_color_policy(not args.no_color)
            pretty_output.set_debug_policy(args.debug)

            pretty_output.title_1('new')
            self.check_override_config_file(args.config_file)
            rule = self.create_default_rule(args)
            config_file = rule.export()
            pretty_output.title_2('kooki.yaml')
            print(config_file)
            write_file('kooki.yaml', config_file)
            pretty_output.title_2()

        except KookiException as e:
            pretty_output.error_step('Errors')
            pretty_output.error(e)

        except Exception as e:
            pretty_output.error_step('Errors')
            pretty_output.error(traceback.format_exc()[:-1])

    def check_override_config_file(self, config_file):
        if os.path.exists(config_file):
            print('The \'kooki.yaml\' config file already exist.')
            response = input('Overide it [y/n] (y): ')
            if response == 'n':
                raise SystemExit(1)
            elif response == 'y' or response == '':
                pass

    def create_default_rule(self, args):

        rule = Rule()

        default_name = 'index'
        rule.set_name(args.name, default_name)

        default_recipe = 'web'
        rule.set_recipe(args.recipe, default_recipe)

        default_template = 'default.html'
        rule.set_template(args.template, default_template)

        default_jars = ['default']
        rule.set_jars(args.jars, default_jars)

        default_content = textwrap.dedent('''\
            # @document.name

            This is a default document generated by *kooki new*.

            Enjoy using **kooki**.

            *@document.author*
            ''')
        rule.set_content(args.content, default_content)

        default_metadata = textwrap.dedent('''\
            document:
                name: Kooki Document
                author: The developpers''')
        rule.set_metadata(args.metadata, default_metadata)

        return rule
