import argparse, em, yaml, os, pretty_output

from karamel.command import Command

from kooki.tools import write_file
from kooki.config import get_kooki_dir


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

default_name = 'index'
default_recipe = 'web'
default_jars = ['default']
default_template = 'default.html'

default_content = '''# @document.name

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

Enjoy using **kooki**.

*@document.author*
'''

default_metadata = '''document:
    name: Kooki Document
    author: The developpers
'''

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')
        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):
        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.command(self.command)

        pretty_output.start_step(args.config_file)
        self.check_override_config_file(args.config_file)

        name = self.handle_name(args)
        recipe = self.handle_recipe(args)
        jars = self.handle_jars(args)
        template = self.handle_template(args)
        metadata = self.handle_metadata(args)
        content = self.handle_content(args)

        config = {
            'name': name,
            'template': template,
            'recipe': recipe,
            'jars': jars,
            'metadata': metadata,
            'content': content}

        generate_config_file(args.config_file, config)

    def check_override_config_file(self, config_file):
        if os.path.exists(config_file):
            response_ok = False
            while not response_ok:
                print('kooki.yaml already exist.')
                response = input("overide it [y/n] (y): ")
                if response == 'n':
                    raise RuntimeError('Existing kooki.yaml has not be changed.')
                elif response == 'y':
                    response_ok = True

    def handle_name(self, args, document_info):
        pretty_output.start_step('name')
        if args.name:
            document_info['name'] = args.name
        else:
            document_info['name'] = default_name
        pretty_output.info(document_info['name'])

    def handle_recipe(self, args, document_info):
        pretty_output.start_step('recipe')
        if args.recipe:
            document_info['recipe'] = args.recipe
        else:
            document_info['recipe'] = default_recipe
        pretty_output.info(document_info['recipe'])

    def handle_jars(self, args, document_info):
        pretty_output.start_step('jars')
        if args.jars:
            document_info['jars'] = []
            for jar in args.jars:
                document_info['jars'].append(jar)
        else:
            document_info['jars'] = default_jars
        pretty_output.info(yaml.safe_dump(document_info['jars'])[:-1])

    def handle_template(self, args, document_info):
        pretty_output.start_step('template')
        if args.template:
            document_info['template'] = args.template
        else:
            document_info['template'] = default_template
        pretty_output.info(document_info['template'])

    def handle_metadata(self, args, document_info):
        pretty_output.start_step('metadata')
        if args.metadata:
            document_info['metadata'] = []
            for metadata in args.metadata:
                document_info['metadata'].append(metadata)
        else:
            document_info['metadata'] = ['metadata.yaml']
            write_file('metadata.yaml', default_metadata)
        pretty_output.info(yaml.safe_dump(document_info['metadata'])[:-1])

    def handle_content(self, args, document_info):
        pretty_output.start_step('content')
        if args.content:
            document_info['content'] = []
            for content in args.content:
                document_info['content'].append(content)
        else:
            document_info['content'] = ['content.md']
            write_file('content.md', default_content)
        pretty_output.info(yaml.safe_dump(document_info['content'])[:-1])
