# -*- coding: utf-8 -*-

# LyricsScreenlet Copyright (C) 2009 by Marcel Dancak <dancakm@gmail.com>

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import dbus
import gobject
import re
from player import PlayerEvents

elapsed_regex = re.compile('(?P<min>\d(\d)?):(?P<sec>\d\d)') # ([d(d)?:dd])
REFRESH_INTERVAL = 1000

class ExailePlayer03(PlayerEvents):
	
	__name__     = "Exaile 0.3"
	timer        = None
	lastTime     = 0
	wasPlaying   = False
	
	def __init__(self, session_bus):
		self.session_bus = session_bus
		
	def is_active(self, dbus_iface):
		return "org.exaile.Exaile" in dbus_iface.ListNames()
		
	def connect(self):
		proxy = self.session_bus.get_object("org.exaile.Exaile", "/org/exaile/Exaile")
		self.playerAPI = dbus.Interface(proxy, "org.exaile.Exaile")
		if self.timer != None:
			gobject.source_remove(self.timer)
		self.timer = gobject.timeout_add(REFRESH_INTERVAL, self.refresh)
		self.lastSong = self.getCurrentFile()

	def disconnect(self):
		if self.timer != None:
			gobject.source_remove(self.timer)
			
	def is_playing(self):
		status = self.playerAPI.Query()
		s = status.find(':')
		e = status.find(',')
		if s != -1 and e != -1:
			return status[s+1:e].strip() == 'playing'
		return False
		
	
	def get_title(self):
		return self.playerAPI.GetTrackAttr('title')
	
	def get_artist(self):
		return self.playerAPI.GetTrackAttr('artist')
	
	def get_album(self):
		return self.playerAPI.GetTrackAttr('album')
		
	def getElapsed(self):
		if self.is_playing():
			elapsedString = self.playerAPI.CurrentPosition()
			match = elapsed_regex.match(elapsedString)
			if match:
				return 60*int(match.group('min'))+int(match.group('sec'))
		return 0

	def getCurrentFile(self):
		filename = self.playerAPI.GetTrackAttr('__loc')
		if filename != '':
			return filename


	def refresh(self):
		try:
			#print "refresh"
			# song change events
			if self.onSongChanged:
				playing_song = self.getCurrentFile()
				if playing_song != self.lastSong:
					if self.onSongChanged != None:
						self.onSongChanged(playing_song)
				self.lastSong = playing_song
		
			# elapsed events
			if self.onElapsed:				
				elapsed = self.getElapsed()
				if elapsed-self.lastTime not in range (0,3):
					#print str(elapsed) +' '+str(self.lastTime)
					self.onElapsed(elapsed)
				self.lastTime = elapsed	
		
			# play/stop events
			#print "is  %s" % self.is_playing()
			#print "was %s" % self.wasPlaying
			
			if self.is_playing() and self.wasPlaying == False and self.onPlay != None:
				self.onPlay()
			if not self.is_playing() and self.wasPlaying == True and self.onStop != None:
				self.onStop()
				
			self.wasPlaying = self.is_playing()
			return True

		except Exception, e:
			print e
			return False
				
