# Copyright (C) 2009-2010 Gloobus Developers
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import os
import dbus
import subprocess
from GenericPlayer import GenericPlayer
from common import Track

class QuodLibetPlayer(GenericPlayer):
    """
        QuodLibet player plugin
    """
    __name__ = 'QuodLibet'
    __version__ = '0.1'
    __author__ = 'Daniel Ribeiro <danielrmt@gmail.com>, Alexandr Grigorcea <cahr.gr@gmail.com>'
    __desc__ = 'API to the QuodLibet Music Player'
    
    DBUS_NAME   = 'net.sacredchao.QuodLibet'
    DBUS_OBJECT = '/net/sacredchao/QuodLibet'
    
    dbus_object = None

    def is_active(self):
        """
            Initializes class, begins dbus listening if DBUS_NAME is provided
            @param d: dbus.Interface
        """
        if self.DBUS_NAME in self.dbus.ListNames():
            return True
        else:
            return False

    def connect(self):
        """
            Connects player
            @return: boolean, True if successful, False if not
        """
        self.dbus_object = dbus.SessionBus().get_object(self.DBUS_NAME, 
            self.DBUS_OBJECT)
        if not self.connected:
            dbus.SessionBus().add_signal_receiver(self.playing_handler, 
                "Unpaused", self.DBUS_NAME, 
                self.DBUS_NAME, self.DBUS_OBJECT)
            dbus.SessionBus().add_signal_receiver(self.paused_handler, 
                "Paused", self.DBUS_NAME, 
                self.DBUS_NAME, self.DBUS_OBJECT)
            dbus.SessionBus().add_signal_receiver(self.song_changed_handler, 
                "SongStarted", self.DBUS_NAME, 
                self.DBUS_NAME, self.DBUS_OBJECT)
            self.connected = True
        return True
            
    def disconnect(self):
        """
            Disconnects player
        """
        if self.connected:
            dbus.SessionBus().remove_signal_receiver(self.playing_handler, 
                "Unpaused", self.DBUS_NAME, 
                self.DBUS_NAME, self.DBUS_OBJECT)
            dbus.SessionBus().remove_signal_receiver(self.paused_handler, 
                "Paused", self.DBUS_NAME, 
                self.DBUS_NAME, self.DBUS_OBJECT)
            dbus.SessionBus().remove_signal_receiver(self.song_changed_handler, 
                "SongStarted", self.DBUS_NAME, 
                self.DBUS_NAME, self.DBUS_OBJECT)
            self.connected = False

    def get_title(self):
        """
            @return: string, title of current playing song
        """
        try:
            return self.dbus_object.CurrentSong()['title']
        except:
            return ""

    def get_album(self):
        """
            @return: string, album name of current playing song
        """
        try:
            return self.dbus_object.CurrentSong()['album']
        except:
            return ""
        
    def get_artist(self):
        """
            @return: string, artist name of current playing song
        """
        try:
            self.dbus_object.CurrentSong()['artist']
        except:
            return ""

    def get_rating(self):
        """
            @return: integer, [0-5] value, representing rating of current
                playing song
        """
        try:
            return round(float(self.dbus_object.CurrentSong()['~#rating']))
        except:
            return 0

    def get_cover_path(self):
        """
            @param data: dictionary, contains info about current playing song.
                optional
            @return: string, path to the album art image of current playing
                songm, (not URI)
        """
        try:
            # QuodLibet uses a picture in the file directory as the cover
            filename = self.getProperty('~filename')
            filename = self.search_cover(filename, None, False)
            if filename:
                return filename
            # But it also keeps a small resized in this path
            filename = os.path.expanduser('~/.quodlibet/cover.png')
            if os.path.exists(filename):
                return filename
        except:
            pass
        return ''

    def get_state(self):
        """
            Returns players actual state.
            @return: string - playing, paused, stopped
        """
        if self.dbus_object.IsPlaying():
            return 'playing'
        else:
            try:
                self.dbus_object.CurrentSong()
                return 'paused'
            except:
                return 'stopped'

    def get_track(self, data=None):
        """
            Prepares a Track object with current playing song data
            
            @param data: dictionary, contains info about current playing song.
                optional
            @return: Track, object with current playing song data
        """
        if not data:
            data = self.dbus_object.CurrentSong()
        
        track = Track(
            title = data['title'],
            album = data['album'],
            artist= data['artist'],
            rating= round(float(data['~#rating'])),
            genre = data['genre'],
            year  = data['date'],
            tracknumber = data['tracknumber'],
            cover = self.get_cover_path()
        )
        return track

    def is_playing(self):
        """
            @return: boolean, True if player is playing, False if not
        """
        return self.dbus_object.IsPlaying()


    def previous(self ,widget, event):
        """
            Changes song to previous
        """
        if self.active:
            os.system('quodlibet --previous')

    def play(self ,widget, event):
        """
            Plays or pauses the player
        """
        if self.active:
            os.system('quodlibet --play-pause')
 

    def next(self ,widget, event):
        """
            Changes song to next
        """
        if self.active:
            os.system('quodlibet --next')

# ============================== PRIVATE METHODS ============================= #

    def getProperty(self, name):
        """
            Get playing music property
        """
        try:
            return self.systemOutput('quodlibet --print-playing "<%s>"' % name)
        except:
            return ''
    
    def systemOutput(self, command):
        """
            Get output from subprocess
        """
        process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
        os.waitpid(process.pid, 0)
        return process.stdout.read().strip()
        
# ================================= HANDLERS ================================= #
    
    def playing_handler(self):
        """
            Handles Unpaused dbus signal, calls state_handler()
        """
        self.state_handler(state='playing')
    
    def paused_handler(self):
        """
            Handles Paused dbus signal, calls state_handler()
        """
        self.state_handler(state='paused')
            
    def song_changed_handler(self, message):
        """
            Handles TrackChanged dbus signal, calls state_handler()
            
            @param message: dictionary with current playing song stats
        """
        track = self.get_track(message)
        self.state_handler(track=track)
