from . import command, audio_fn
from sh import ffmpeg as ffmpeg_unbaked, cp as cp_unbaked
import sh
import os
import traceback
import logging
logger = logging.getLogger('musicleg')

ffmpeg = ffmpeg_unbaked.bake(_tty_out=False)
cp = cp_unbaked.bake(_tty_out=False)

@command('voeg toe aan muziekbeen( ([^=;]+=[^;/]+;)+)?', pass_groups=True, additional_match_fn=audio_fn)
def voeg_toe(bea, bot, update, audio, groups):
    """
    Voegt een audiobestand toe aan de database van Muziekbeen.
    Dat rare ding aan het einde van de match regex is een taglijst;
    zie dit commandovoorbeeld:

    ?voeg toe aan Muziekbeen artist=Rick Astley;title=Never Gonna Give You Up;
    """
    tags = {}
    if groups[0]:
        logger.info(f"Groups: {groups}")
        tags = groups[0][1:].strip(';').split(';')
        tags = {k:v for k, v in [tag.split('=') for tag in tags]}
        logger.info(f"Tags: {tags}")

    if (not audio.performer) and 'artist' not in tags:
        return bea.reply("In dat bestand staat geen artiest, en je hebt geen artist-tag meegegeven.")

    if (not audio.title) and 'title' not in tags:
        return bea.reply("In dat bestand staat geen titel, en je hebt geen title-tag meegegeven.")

    artist = tags.get('artist') or audio.performer
    title  = tags.get('title') or audio.title
    album  = tags.get('album') or ''


    fl = audio.get_file()
    fl.download(custom_path='audio_input.audio')

    try:
        ffmpeg('-y', '-i', 'audio_input.audio', '-acodec', 'libopus', '-metadata:s:a:0', 'artist='+artist, '-metadata:s:a:0', 'title='+title, f'{artist}_{album}_{title}.opus')
        cp(f'{artist}_{album}_{title}.opus', '/opt/muziekbeen/data')
        os.unlink(f'{artist}_{album}_{title}.opus')
        os.unlink('audio_input.audio')
    except sh.ErrorReturnCode as e:
        logger.error(e.stderr)
        traceback.print_exc()
    else:
        bea.reply(f"Bestand toegevoegd aan Muziekbeen met tags: artist {artist}, title {title}{', album ' + album if album else ''}")

def init(bea, _config):
    return [voeg_toe]
