#!/usr/bin/env python3

import mpd
import sys
import yaml
import subprocess

ACTIONS = [
    'append',
    'play',
]

# Get colors for dmenu
with open('/home/meow/.colorize/current/colors.yaml') as f:
    colors = yaml.load(f)


def display_dmenu(data_in=None):
    if data_in:
        data_in = data_in.encode('utf-8')
    dmenu = subprocess.Popen(
        ['dmenu2', '-i', '-p', 'Music >', '-dim', '0.4',
         '-nb', colors['background'], '-nf', colors['foreground'],
         '-sb', colors['bblue'], '-sf', colors['bwhite']],
        stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    return dmenu.communicate(data_in)[0].decode('utf-8').rstrip()


if __name__ == '__main__':
    # Get input from user
    client = mpd.MPDClient(use_unicode=True)
    client.connect('localhost', 6600)
    artist = display_dmenu()
    if not artist:
        sys.exit(1)

    # Get artist albums
    albums = client.list('album', artist)
    if not albums:
        display_dmenu('No album found for {}'.format(artist))
        sys.exit(1)
    album = display_dmenu('\n'.join(albums))

    # Get album uri
    try:
        uri = client.search('album', album, 'artist', artist)[0]['x-albumuri']
    except KeyError:
        display_dmenu('Non spotify albums not handled')
        sys.exit(1)

    # Choose action
    result = display_dmenu('\n'.join(ACTIONS))
    if not result:
        sys.exit(1)
    if result == 'append':
        client.add(uri)
    else:
        client.clear()
        client.add(uri)
        client.play(0)
