#!/usr/bin/env python

from commands import getoutput
import dbus
import signal
import string
from time import sleep
from os import system
import sys

awn = ""
alternate = 1
current_cover = "-"
old_rem = 0
minutes = -1

# dbus connection
def get_dbus_connection():
    print "creating dbus object",
    bus = dbus.SessionBus()
    try:
	obj = bus.get_object("com.google.code.Awn", "/com/google/code/Awn")
    except:
        print "no service provided"
        return ""
    return dbus.Interface(obj, "com.google.code.Awn")

# termination handling
def cleanup():
    global current_cover
    if current_cover != "":
        print "unsetting cover and progress"
        if getoutput("pidof avant-window-navigator") != "":
            try:
            	awn.UnsetInfoByName("amarok")
            	awn.UnsetTaskIconByName("amarok")
	    except:
		print "unexpected Error"
        current_cover = "-"

def sigterm_handler(signum, frame):
        print "unsetting cover and progress"
        if getoutput("pidof avant-window-navigator") != "":
            try:
                awn.UnsetInfoByName("amarok")
                awn.UnsetTaskIconByName("amarok")
	    except:
		print "unexpected Error"
        sys.exit(0)

signal.signal(signal.SIGTERM, sigterm_handler)

if getoutput("pidof avant-window-navigator") != "":
    awn = get_dbus_connection()
    try:
        awn.UnsetInfoByName("amarok")
        awn.UnsetTaskIconByName("amarok")
    except:
	print "unexpected Error"

# main loop
while(1):
    if getoutput("pidof avant-window-navigator") != "":
        if awn == "":
            awn = get_dbus_connection()
        print "\nawn is running"
        if (getoutput('dcop amarok player isPlaying') == "true"):
            print "amarok is playing a track"
            total = int(getoutput('dcop amarok player trackTotalTime 2> /dev/null'))
            if total > 0:
                print "setting remaining time",
                current = int(getoutput('dcop amarok player trackCurrentTime 2> /dev/null'))
                rem = int(total - current)
                minutes = rem/60
		secs = rem%60
		print str(minutes)+':'+string.zfill(secs,2)
		try:
		    awn.SetInfoByName("amarok",str(minutes)+':'+string.zfill(secs,2))
		    print "[done]"
                except:
                    print "unexpected Error" 
                print "setting cover",
                cover = getoutput('dcop amarok player coverImage 2> /dev/null')
		print "[found:",cover,"]"
		if cover.find('nocover.png') < 0 and (current_cover != cover or current_cover == "" or current_cover == "-"):
                    coverpath = "cp "+cover+" /tmp/amarok-cover.png"
                    system(coverpath)
                    current_cover = cover
		    try:
                        awn.SetTaskIconByName ("amarok", "/tmp/amarok-cover.png")
                        print "[done:new]"
		    except:
                        print "unexpected Error" 
                elif cover.find('nocover.png') >= 0:
		    try:
                        awn.UnsetTaskIconByName("amarok")
    		    except:
			print "unexpected Error"
		else:	
                    print "[done:old]"
            else:
                print "not playing"
                cleanup()
        elif getoutput('dcop amarok player status')=='1':
   	    print "paused"
	    if minutes == -1:
		total = int(getoutput('dcop amarok player trackTotalTime 2> /dev/null'))
		current = int(getoutput('dcop amarok player trackCurrentTime 2> /dev/null'))
                rem = int(total - current)
                minutes = rem/60
		secs = rem%60
		print str(minutes)+':'+string.zfill(secs,2)
		try:
		    awn.SetInfoByName("amarok",str(minutes)+':'+string.zfill(secs,2))
		    print "[done]"
                except:
                    print "unexpected Error"
		print "setting cover"
		cover = getoutput('dcop amarok player coverImage 2> /dev/null')
                if cover.find('nocover.png') < 0 and (current_cover != cover or current_cover == "" or current_cover == "-"):
                    coverpath = "cp "+cover+" /tmp/amarok-cover.png"
                    system(coverpath)
                    current_cover = cover
		    try:
                        awn.SetTaskIconByName ("amarok", "/tmp/amarok-cover.png")
                        print "[done:new]"
		    except:
                        print "unexpected Error" 
                elif cover.find('nocover.png') >= 0:
		    try:
                        awn.UnsetTaskIconByName("amarok")
    		    except:
			print "unexpected Error"
		else:	
                    print "[done:old]"			
	    if alternate:
		try:
   	 	    awn.SetInfoByName("amarok",str(minutes)+':'+string.zfill(secs,2))
		except:
		    awn = ""
		    cover = "-"
		    minutes = -1
	    else:
		try:
		    awn.SetInfoByName("amarok",'pause')
		except:
		    awn = ""
		    cover = "-"
		    minutes = -1
	    alternate = 1-alternate
	else:
            print "not playing"
            cleanup()
    else:
	awn=""
	cover="-"
	minutes = -1
    if getoutput("pidof amarok") == "" and getoutput("pidof amarokapp") == "":
        print "amarok not running"
        cleanup()
        print "exiting"
        exit()
    sleep(1)
