#!/usr/bin/env python3

import pathlib

import click

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


@click.command()
@click.option('--config', '-c', 'config_path', type=click.Path(dir_okay=False, path_type=pathlib.Path), default=mucus.config.default_path())
@click.option('--version', is_flag=True)
def main(config_path, version):
    if version:
        click.echo(mucus.__version__)
        return

    config = mucus.config.load(config_path)
    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(config.get('prompt', '\u1e43 '))
            except EOFError:
                break

    history = mucus.history.History()
    aliases = config.get('aliases', {})

    with history:
        for line in inputs():
            try:
                loader = mucus.command.Loader(line=line, aliases=aliases)
            except mucus.exception.NoSuchCommand:
                name = config.get('default_command', 'search')
                try:
                    loader = mucus.command.Loader(name=name, 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': config,
                       '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
