import gobject
import gtk
import os
import subprocess

__name = 'Gajim Status Changer'
__version = '0.01'
__author = "Natan 'whatah' Zohar"
__blurb = "Gajim Status Changer will change the current status' message to reflect the song playing in mpd"
__class = "Gajim"

class GajimTalker:
    def __init__(self):
        self.command = "gajim-remote"

    def change_status(self, message=None, account=None):
        status = self.get_status().strip()
        cmd = ["change_status", status]
        if message:
            cmd.append('"%s"' % message)
        if account:
            cmd.append(account)
        return self.talkto(' '.join(cmd))

    def get_status(self):
        return self.talkto('get_status')

    def talkto(self, cmd):
        cmd = "%s %s" % (self.command, cmd)
        return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()


class Gajim:

    # called when we load the plugin. we get passed the mainWindow, plugin menu
    # item as well as a connection to mpd.
    def _init(self, data, pympd):
        self.xml, self.pluginMenu, self.pympd, self.base_dir, self.parser = data
        self.data = data
        self.gt = GajimTalker()
        self.old_state = None

    def _conf(self, hasConf=False):
        if hasConf:
            return False

    # update plugin, data is of type mpdclient.Status
    def _spin(self, data, songChanged=False):
        song = self.pympd.getCurrentSong()
        if data.state == 'play':
            if songChanged:
                msg = ""
                if song.artist and song.artist.strip() != "":
                    msg += song.artist
                if song.title and song.title.strip() != "":
                    msg += " - " + song.title
                gobject.idle_add(self.gt.change_status, msg)

        if data.state != self.old_state:
            if data.state == 'stop' or data.state == 'pause':
                msg = ""
                gobject.idle_add(self.gt.change_status)
            if data.state == 'play':
                msg = ""
                if song.artist and song.artist.strip() != "":
                    msg += song.artist
                if song.title and song.title.strip() != "":
                    msg += " - " + song.title
                gobject.idle_add(self.gt.change_status, msg)
            self.old_state = data.state
                
    # called on plugin unloaded
    def _unload(self):
        self.gt.change_status()
        return
