#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# NowPlaying Client for MPD (Music Player Daemon)

import commands
import time
import sys
import nowplaying

class App(object):
	def __init__(self, api_key, api_url = "http://np.malte70.de/api/"):
		self.client = nowplaying.NowPlayingClient(api_key)
		self.client.api_url = api_url
		
	def getCurrentTrack(self):
		return commands.getstatusoutput('mpc current')[1]
		
	def sendTrack(self, i, t):
		self.client.sendTrack(i, t)
		
	def mainLoop(self):
		"""
		main loop. gets current song via mpc output, and if it changed,
		send it to the API.
		"""
		oldsong = ''
		try:
			while True:
				newsong = self.getCurrentTrack
				if oldsong!=newsong and newsong != "":
					oldsong = newsong
					_interpreter, _title = newsong.split(" - ")
					self.sendTrack(_interpreter, _title)
				time.sleep(1)
		except KeyboardInterrupt:
			pass

def main():
	app = App("ABCDE")
	app.mainLoop()

if __name__=="__main__":
	main()
