import pathlib

import mucus.command


class Command(mucus.command.Command):
    def __call__(self, client, config, player, **kwargs):
        if player.song is None:
            return

        data = client.stream(player.song)

        media = next(data)
        if media is None:
            raise Exception

        source = next(data)
        if source is None:
            raise Exception

        root = pathlib.Path(config['download']['directory'])
        path = root.joinpath(player.song['ART_NAME'], player.song['ALB_TITLE'])
        path.mkdir(parents=True, exist_ok=True)
        path = path.joinpath(f'{player.song['TRACK_NUMBER']:02} {player.song['SNG_TITLE']}.flac')

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