# $Id: np_simple.py 51 2007-09-22 12:40:49Z kostix $
# "Now playing simple" plugin for Quod Libet: writes info about
# currently playing song to a text file.
# Format is similar to ~/.quodlibet/current, but it contains less data
# (only what is needed for XEP-0118) and also tracks playing/paused state.
# Written by Konstantin Khomoutov <flatworm@users.sourceforge.net>
# Inspired by JEP118 plugin.

# TODO
# ? Dump all available info.
# ? Dump song info also on "paused" state.

import os
import util
import atexit

from plugins.events import EventPlugin

outfile = os.path.expanduser("~/.quodlibet/now_playing")
format = """\
status=%s
artist=%s
title=%s
album=%s
tracknumber=%s
~#length=%d
"""

def write_out(what):
	try:
		f = file(outfile, 'w')
		f.write(what.encode('utf-8'))
	except EnvironmentError: pass
	else: f.close()

def report_inactive(state):
	write_out("status=%s\n" % state)

class np_simple(EventPlugin):
	PLUGIN_ID      = 'np_simple'
	PLUGIN_NAME    = 'Now Playing Simple'
	PLUGIN_DESC    = 'Outputs simple now playing info to a text file'
	PLUGIN_ICON    = 'gtk-save'
	PLUGIN_VERSION = '0.3'

	def report_song_info(self, song):
		write_out(format % (
				'playing',
				song.comma('artist'),
				song.comma('title'),
				song.comma('album'),
				song('tracknumber'),
				song('~#length')))

	def plugin_on_song_started(self, song):
		if song:
			self.song = song
			self.report_song_info(song)
		else:
			report_inactive('paused')

	def plugin_on_paused(self):
		report_inactive('paused')

	def plugin_on_unpaused(self):
		self.report_song_info(self.song)

	def plugin_on_song_ended(self, song, stopped):
		report_inactive('paused')
		
	def disabled(self):
		report_inactive('inactive')

atexit.register(report_inactive, 'inactive')

