# Copyright (c) 2015 Daniel Greve
# Licensed under the MIT License

"""Adds the results of a beets query to MPD's current playlist"""

from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
from beets import ui
from beets import config
from os.path import relpath
import os
import socket
import sys

"""Taken from Adrian Sampson's MPD Update Plugin
https://github.com/sampsyo/beets/blob/master/beetsplug/mpdupdate.py
"""
class BufferedSocket(object):

    """Socket abstraction that allows reading by line."""

    def __init__(self, host, port, sep='\n'):
        if host[0] in ['/', '~']:
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.sock.connect(os.path.expanduser(host))
        else:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((host, port))
        self.buf = ''
        self.sep = sep

    def readline(self):
        while self.sep not in self.buf:
            data = self.sock.recv(1024)
            if not data:
                break
            self.buf += data
        if '\n' in self.buf:
            res, self.buf = self.buf.split(self.sep, 1)
            return res + self.sep
        else:
            return ''

    def send(self, data):
        self.sock.send(data)

    def close(self):
        self.sock.close()

    # Sends command to socket and listens for response
    def chat(self, message, error_message):
        self.send(message)
        response = self.readline()
        if 'OK' not in response:
            ui.print_(ui.colorize('red', error_message))
            ui.print_(ui.colorize('red', repr(response)))
            self.send('close\n')
            self.close

def mpd_add(lib, opts, args):
    """Converts results from a query to relative uris and sends them to MPD.
    """

    # Read user configuration.
    host = config['mpd']['host'].get()
    port = config['mpd']['port'].get()
    password = config['mpd']['password'].get()
    music_directory = config['mpd']['music_directory'].get()

    # Print how many items are being added
    def aye(item_list, item_type):
        num = len(item_list)
        if num > 1:
            item_type += 's'
        if num == 0:
            ui.print_(ui.colorize('red', 'No items match your query.'))
            return
        elif num > 100:
            ui.print_(ui.colorize('red', 'Add %s %s to playlist?' % (num, item_type)))
            if ui.input_options(('Yes', 'No')) == 'n':
                sys.exit(0)
        ui.print_(ui.colorize('brown', 'Adding %s %s to playlist...' % (num, item_type)))

    # Perform query and retrieve the absolute path to the results.
    paths = []
    if opts.album:
        for albums in lib.albums(ui.decargs(args)):
            paths.append(albums.path)
        aye(paths, 'album')
    else:
        for items in lib.items(ui.decargs(args)):
            paths.append(items.path)
        aye(paths, 'track')

    # Generate relative paths of the results from user specified directory.
    playlist = [relpath(item, music_directory) for item in paths]

    # Initialize client object and connect to MPD.
    client = BufferedSocket(host, port)
    response = client.readline()
    if 'OK MPD' not in response:
        ui.print_(ui.colorize('red', 'MPD Connection failed', repr(response)))
        return

    # Authenticate with password if one is provided.
    if password:
        client.chat('password "%s"\n' % password, 'Authentication failed:')

    # Optionally clear current playlist before adding music.
    if opts.clear:
        client.chat('clear\n', 'Clearing playlist failed:')

    # Iterate through URIs and send them to MPD.
    for uri in playlist:
        client.chat('add "%s"\n' % uri, 'Adding music failed:')

    # Send the play command to MPD and close the connection.
    client.chat('play\n', 'Playing failed:')
    client.send('close\n')
    client.close()


class MPDAddPlugin(BeetsPlugin):

    def __init__(self):
        super(MPDAddPlugin, self).__init__()

        config['mpd'].add({
            'host': u'localhost',
            'port': 6600,
            'password': u'',
            'music_directory': config['directory'].as_filename(),
        })

    def commands(self):
        mpd_add_command = Subcommand(
            'add',
            help='add music to your playlist'
        )
        mpd_add_command.parser.add_option(
            '-a', '--album',
            action='store_true', default=False,
            help='add albums instead of tracks'
        )
        mpd_add_command.parser.add_option(
            '-c', '--clear',
            action='store_true', default=False,
            help='clears current playlist before adding music'
        )
        mpd_add_command.func = mpd_add
        return [mpd_add_command]

@@ -2207,24 +2207,26 @@
 's'%0A        
+el
 if num == 0:

Fix control flow statment