import argparse
import shlex

import click

import mucus.command
import mucus.config


class Command(mucus.command.Command):
    def __call__(self, command, config, **kwargs):
        try:
            config['aliases']
        except KeyError:
            config['aliases'] = {}

        if command['args'].strip() == '':
            for alias, command in config['aliases'].items():
                click.echo(' '.join([
                    click.style(alias, fg='red'),
                    '=',
                    click.style('"' + command +'"', fg='green')
                ]))
            return
        
        parser = argparse.ArgumentParser(exit_on_error=False)
        parser.add_argument('alias')
        parser.add_argument('command', nargs='*')
        try:
            args = parser.parse_args(shlex.split(command['args']))
        except argparse.ArgumentError as e:
            raise mucus.exception.CommandException(e)

        config['aliases'][args.alias] = shlex.join(args.command)
        mucus.config.dump(config)
