#!/usr/bin/env python

# dig jazz currently playing applet
# (C) 2007 Ian Wienand <ianw@ieee.org>
# Released under GPL

import sys
import time
import math

import urllib
from xml.sax import saxutils, handler, make_parser

import pygtk
pygtk.require('2.0')

import gtk, gtk.gdk
import gnomeapplet
import gnome.ui
import pynotify

ICON_FILE = '/usr/share/icons/dig-jazz-applet.svg'

ABC_ROOT = 'http://www.abc.net.au'
DIG_STATUS_XML = ABC_ROOT + '/dig/jazz/xml/nowplaying.xml'

xml_elements = ["title", "artist", "album", "recordlabel", "releasedate",
                "duration", "imageURL", "info"]

song = {}

class XMLParser(handler.ContentHandler):
    def __init__(self):
        self.text = ''

    def startDocument(self):
        self.new_song = {}
    
    def startElement(self, name, attrs):
        if name in xml_elements:
            self.parent = name
            self.text = ""
        else:
            # the "info" element includes embedded
            # HTML
            self.text += '<' + name.lower()
            for (name, value) in attrs.items():
                # strip out stuff libnotify doesn't seem to like, including making things
                # lower case
                if name == "target":
                    continue
                self.text += ' %s="%s"' % (name.lower(), saxutils.escape(value))
            self.text += '>'

    def characters(self, content):
        self.text += content

    def endElement(self, name):
        if name == self.parent:
            self.new_song[name] = self.text
        else:
            self.text += '</' + name.lower() + '>'
        
    def endDocument(self):
        global song
        song = self.new_song

class DigJazzApplet:

    def __init__(self, applet, iid):

        pynotify.init("digg-jazz-applet")

        self.applet = applet
        self.hbox = gtk.HBox()

        image = gtk.Image()
        size = self.applet.get_size()
        self.pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(ICON_FILE, size-4, size-4)
        image.set_from_pixbuf(self.pixbuf)

        ev_box = gtk.EventBox()
        ev_box.add(image)
        ev_box.connect("button-press-event", self.button_clicked)
        self.hbox.add(ev_box)
        
        self.applet.add(self.hbox)

        self.propxml = """
        <popup name="button3">
        <menuitem name="Item 3" verb="About" label="_About..." pixtype="stock" pixname="gnome-stock-about"/>
        </popup>
        """
                
        self.verbs = [ ( "About", self.about_info ) ]
        
        self.applet.show_all()


    def button_clicked(self,widget,event):

        # if this is a right click, don't handle it
        if event.button == 3:
            self.applet.setup_menu(self.propxml,self.verbs,None)
            return False

        xml = urllib.urlretrieve(DIG_STATUS_XML)

        parser = make_parser()
        parser.setContentHandler(XMLParser())

        try:
            parser.parse(xml[0])
            urllib.urlcleanup()
        except:
            n = pynotify.Notification("Dig Jazz currently playing",
                                      '<b>Invalid Data Received</b>')
            n.attach_to_widget(self.hbox)
            n.show()
            urllib.urlcleanup()

        duration = float(song["duration"])/1000
        minutes = int(math.floor(duration / 60))
        seconds = int(duration - minutes*60)

        content =  """
        <b>Track</b> - %s
        <b>Artist</b> - %s
        <b>Album</b> - %s
        <b>Label</b> - %s
        <b>Release Date</b> - %s
        <b>Duration</b> - %s
        <b>Link</b> - %s
        """  % (song["title"],song["artist"],song["album"],
                song["recordlabel"],song["releasedate"],
                "%sm %ss" % (minutes, seconds),
                song["info"])

        cover = urllib.urlopen(ABC_ROOT + song["imageURL"])
        image = gtk.gdk.PixbufLoader()
        image.write(cover.read())
        image.close()

        n = pynotify.Notification("Dig Jazz currently playing", content)
        n.attach_to_widget(self.hbox)
        n.set_icon_from_pixbuf(image.get_pixbuf())
        n.show()

    def about_info(self,event,data=None):
        about = gnome.ui.About("Digg Jazz Currently Playing Applet",
                               "1.0",
                               ('Copyright \xc2\xa9 2007 Ian Wienand. Released under GPL.'),
                               ("Applet to show what is playing on ABC Dig Jazz."),
                               [ "Ian Wienand <ianw@ieee.org>" ],
                               [],
                               "",
                               self.pixbuf)
        about.show()



def DigJazz_applet_factory(applet, iid):
    DigJazzApplet(applet, iid)
    return True

if len(sys.argv) == 2:
    if sys.argv[1] == "run-in-window":
        main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        main_window.set_title("Python Applet")
        main_window.connect("destroy", gtk.main_quit)
        app = gnomeapplet.Applet()
        DigJazz_applet_factory(app, None)
        app.reparent(main_window)
        main_window.show_all()
        gtk.main()
        sys.exit()

if __name__ == "__main__":
    gnomeapplet.bonobo_factory("OAFIID:GNOME_DigJazzApplet_Factory",
                               gnomeapplet.Applet.__gtype__,
                               "Show currently playing Dig Jazz Song", "1.0", DigJazz_applet_factory)
