#!/usr/bin/env python2
import socket

class MPC:
    def __init__(self, ip="127.0.0.1", port=6600):
        self._sock = socket.socket()
        self._sock.connect((ip, port))

    def cmd(self, command):
        self._sock.send(command + "\n")

        data = ""
        while not data.endswith("\nOK\n"):
            received = self._sock.recv(1024)
            if not received:
                break
            data += received

        results = {}
        for line in data.split("\n"):
            if line.startswith("OK"):
                continue

            line = line.split(":")
            if len(line) < 2:
                continue

            results[line[0]] = ":".join(line[1:]).lstrip()

        return results

    def now_playing(self):
        status          = self.cmd("status")
        song            = self.cmd("playlistid %s" % status["songid"])
        song["Elapsed"] = float(status["elapsed"])
        song["Time"]    = float(song["Time"])
        return song

def seconds(seconds):
    minutes = seconds / 60
    seconds = seconds % 60
    return "%d:%.2d" % (minutes, seconds)

song_format = "\005{R}%s \005{B}(\005{Y}%s/%s\005{B}) \005{R}%s\005{B}"
mpd_client  = MPC()
song        = mpd_client.now_playing()
elapsed     = seconds(song["Elapsed"])
total       = seconds(song["Time"])

print song_format % (song["Artist"], elapsed, total, song["Title"])
