import argparse
import pathlib
import shlex

import click
import halo

import mucus.command
import mucus.config
import mucus.deezer.page
import mucus.deezer.stream



class Command(mucus.command.Command):
    def __call__(self, client, command, config, player, **kwargs):
        parser = argparse.ArgumentParser(exit_on_error=False)
        parser.add_argument('-a', '--album', action='store_true')
        parser.add_argument('-d', '--directory')
        args = parser.parse_args(shlex.split(command['args']))

        if args.directory is not None:
            try:
                config['download']
            except KeyError:
                config['download'] = {}
            config['download']['directory'] = args.directory
            mucus.config.dump(config)

        if player.song is None:
            return

        def download(song, album=None):
            stream = mucus.deezer.stream.stream(song, client.data.license_token)

            media = next(stream)
            if media is None:
                raise mucus.exception.NoMedia

            source = next(stream)
            if source is None:
                raise mucus.exception.NoSource

            root = pathlib.Path(config['download']['directory'])

            def _(s):
                return s.replace('/', '|')

            if album is None:
                path = root.joinpath(_(song['ART_NAME']), _(song['ALB_TITLE']))
            else:
                path = root.joinpath(_(album['ART_NAME']), _(album['ALB_TITLE']))
            path.mkdir(parents=True, exist_ok=True)
            ext = media['format'] == 'FLAC' and 'flac' or 'mp3'
            path = path.joinpath(f'{int(song['TRACK_NUMBER']):02} - {_(song['SNG_TITLE'])}.{ext}')

            with path.open('wb') as f:
                for chunk in stream:
                    f.write(chunk)

        spinner = halo.Halo()
        if args.album:
            page = mucus.deezer.page.Album(client=client, alb_id=player.song['ALB_ID'])
            for song in page.data['SONGS']['data']:
                spinner.start(f'{int(song['TRACK_NUMBER']):02} - {song['SNG_TITLE']}')
                try:
                    download(song, album=page.data['DATA'])
                except mucus.exception.MucusError:
                    spinner.fail()
                else:
                    spinner.succeed()
        else:
            with spinner:
                try:
                    download(player.song)
                except mucus.exception.MucusError:
                    spinner.fail()
                else:
                    spinner.succeed()
