#!/usr/bin/env python3

import click

import mucus.command
import mucus.config
import mucus.deezer
import mucus.exception
import mucus.history
import mucus.player


@click.command(context_settings={'default_map': mucus.config.load()})
@click.option('--alias', '-a', 'aliases', type=(str, str),
              metavar='<name> <command>', multiple=True)
@click.option('--default', '-d', default='search', show_default=True,
              metavar='<command>', help='default command')
@click.option('--prompt', '-p', default='m ', show_default=True)
@click.option('--version', is_flag=True)
@click.pass_context
def main(ctx, aliases, default, prompt, version):
    if version:
        click.echo(mucus.__version__)
        return

    aliases = dict(aliases)
    history = mucus.history.History('cli')
    client = mucus.deezer.client.Client()

    if client.data.user_id == 0:
        click.secho('not logged in', fg='red')

    player = mucus.player.Player(client)

    try:
        player.start()
    except mucus.exception.MucusException as e:
        raise click.ClickException(e)

    def inputs():
        while True:
            try:
                yield input(prompt)
            except EOFError:
                break

    with history:
        for line in inputs():
            try:
                loader = mucus.command.Loader(line=line, aliases=aliases)
            except mucus.exception.NoSuchCommand:
                try:
                    loader = mucus.command.Loader(name=default, args=line)
                except mucus.exception.NoSuchCommand as e:
                    raise click.ClickException(e)

            context = {'client': client,
                       'command': {'line': line,
                                   'name': loader.name,
                                   'args': loader.args},
                       'config': ctx.default_map,
                       'history': history,
                       'player': player}

            runner = mucus.command.Runner(loader, context)

            try:
                runner()
            except mucus.exception.CommandException as e:
                click.echo(e)
            except mucus.exception.Exit:
                break
