#!/usr/bin/env python

import sys
import time
import math

import urllib
import simplejson as json

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'

# keeps moving about!  now in JSON
DIG_STATUS_XML = "http://abcjazz.net.au/player-data.php"

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 _parse_input(self):
        songs = [None, None, None]
        http_response = urllib.urlretrieve(DIG_STATUS_XML)        
        raw_info = open(http_response[0], "r")
        raw_songs = json.loads(raw_info.read())
        urllib.urlcleanup()

        for s in raw_songs:
            # clean up the tracknote so it displays
            s['trackNote'] = s['trackNote'].replace('target="_blank"','')
            s['trackNote'] = s['trackNote'].replace('<A HREF=','<a href=')
            s['trackNote'] = s['trackNote'].replace('</A>','</a>')

            # put into a simple ordered list
            if s['playing'] == 'now':
                songs[0] = s
            elif s['playing'] == 'past':
                songs[1] = s
            elif s['playing'] == 'next':
                songs[2] = s
            else:
                raise TypeError

        return songs
        
    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

        try:
            songs = self._parse_input()
        except:
            n = pynotify.Notification("Dig Jazz currently playing",
                                      '<b>Invalid Data Received</b>')
            n.attach_to_widget(self.hbox)
            n.show()
            urllib.urlcleanup()

        # there should be 3 songs; 0 is the current, 1 is previous, 2
        # is upcoming
        song = songs[0]

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

        content = '<b>Track</b> - %s\n'     \
                  '<b>Artist</b> - %s\n'     \
                  '<b>Album</b> - %s (%s)\n' \
                  '<b>Duration</b> - %s\n'   \
                  '<b>Link</b> - %s\n'       \
                  '<span foreground="#aaa"><b>Previous</b> - %s (%s)</span>\n' \
                  '<span foreground="#aaa"><b>Next</b> - %s (%s)</span>\n'% (
            song["title"],
            song["artistName"],
            song["albumName"],
            song["dateCopyrighted"],
            "%sm %ss" % (minutes, seconds),
            song["trackNote"],
            songs[1]["title"], songs[1]["artistName"],
            songs[2]["title"], songs[2]["artistName"]
            )
        print content
        cover = urllib.urlopen(song["albumImage"])
        image = gtk.gdk.PixbufLoader()
        try:
            # sometimes this fails ...
            image.write(cover.read())
            image.close()
        except:
            image = None

        n = pynotify.Notification("Dig Jazz currently playing", content)
        n.attach_to_widget(self.hbox)
        if not image is None:
            n.set_icon_from_pixbuf(image.get_pixbuf())
        n.set_timeout(pynotify.EXPIRES_NEVER)
        n.show()

        # reset
        songs = []

    def about_info(self,event,data=None):
        about = gnome.ui.About("Digg Jazz Currently Playing Applet",
                               "3.0",
                               ('Copyright \xc2\xa9 2007-2010 Ian Wienand. Released under GPL.'),
                               ("Applet to show what is playing on ABC Dig Jazz."),
                               [ "Ian Wienand <ian@wienand.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", "2.0", DigJazz_applet_factory)

