# 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 urllib
from GenericPlayer import GenericPlayer
from common import Track

class BansheePlayer(GenericPlayer):
    """
        Banshee player plugin
    """
    __name__ = 'Banshee'
    __version__ = '0.1'
    __author__ = 'BadChoice <guitarboy000@gmail.com>, Alexandr Grigorcea <cahr.gr@gmail.com>'
    __desc__ = 'API to the Banshee Music Player'
    
    DBUS_NAME   = 'org.bansheeproject.Banshee'
    DBUS_OBJECT = '/org/bansheeproject/Banshee/PlayerEngine'
    
    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.session_bus = dbus.SessionBus()
        self.dbus_object = self.session_bus.get_object(self.DBUS_NAME, 
            self.DBUS_OBJECT)
        if not self.connected:
            self.session_bus.add_signal_receiver(self.playing_changed_handler, 
                "StateChanged", 'org.bansheeproject.Banshee.PlayerEngine', 
                'org.bansheeproject.Banshee', 
                '/org/bansheeproject/Banshee/PlayerEngine')
                
            self.session_bus.add_signal_receiver(self.song_changed_handler, 
                "EventChanged", 'org.bansheeproject.Banshee.PlayerEngine', 
                'org.bansheeproject.Banshee', 
                '/org/bansheeproject/Banshee/PlayerEngine')
            self.connected = True
        return True
            
    def disconnect(self):
        """
            Disconnects player
        """
        if self.connected:
            self.session_bus.remove_signal_receiver(self.playing_changed_handler, 
                "StateChanged", 'org.bansheeproject.Banshee.PlayerEngine', 
                'org.bansheeproject.Banshee', 
                '/org/bansheeproject/Banshee/PlayerEngine')
                
            self.session_bus.remove_signal_receiver(self.song_changed_handler, 
                "EventChanged", 'org.bansheeproject.Banshee.PlayerEngine', 
                'org.bansheeproject.Banshee', 
                '/org/bansheeproject/Banshee/PlayerEngine')
            self.connected = False
    
    def get_title(self):
        """
            @return: string, title of current playing song
        """
        try:
            return self.dbus_object.GetCurrentTrack()['name']
        except:
            return ""
    
    def get_album(self):
        """
            @return: string, album name of current playing song
        """
        try:
            return self.dbus_object.GetCurrentTrack()['album']
        except:
            return ""
        
    def get_artist(self):
        """
            @return: string, artist name of current playing song
        """
        try:
            return self.dbus_object.GetCurrentTrack()['artist']
        except:
            return ""
        
    def get_rating(self):
        """
            @return: integer, [0-5] value, representing rating of current
                playing song
        """
        try:
            return self.dbus_object.GetCurrentTrack()['rating']
        except:
            return 0

    def get_cover_path(self, filename=False):
        """
            @param filename: string, contains path to current playing song.
                optional
            @return: string, path to the album art image of current playing
                songm, (not URI)
        """
        try:
            if not filename:
                filename = self.dbus_object.GetCurrentUri()
            filename = self.search_cover(filename)
            if filename:
                return filename
            else:
                path = "~/.cache/album-art/" + self.dbus_object.GetCurrentTrack()['artwork-id']+".jpg"
                path = os.path.expanduser(path)
                if os.path.exists(path):
                    return path
        except:
            pass
        return ''

    def get_state(self,state=None):
        if not state:
            state = self.dbus_object.GetCurrentState()
        if state == 'idle':
            return 'stopped'
        return state
        
    
    def is_playing(self):
        """
            @return: boolean, True if player is playing, False if not
        """
        state = self.dbus_object.GetCurrentState()
        print state
        if state == "playing":
            return True
        else:
            return False
    
    def previous(self, widget, event):
        """
            Changes song to previous
        """
        if self.active:
            self.session_bus.get_object(self.DBUS_NAME, '/org/bansheeproject/Banshee/PlaybackController').Previous(True)

    def play(self, widget, event):
        """
            Plays or pauses the player
        """
        if self.active:
            self.dbus_object.TogglePlaying()
        
    def next(self, widget, event):
        """
            Changes song to next
        """
        if self.active:
            dbus_obj = self.session_bus.get_object(self.DBUS_NAME, '/org/bansheeproject/Banshee/PlaybackController')
            dbus_obj.Next(True)

    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:
            try:
                data = self.dbus_object.GetCurrentTrack()
            except dbus.DBusException:
                if self.is_active():
                    self.connect()
                    data = self.dbus_object.GetCurrentTrack()
                else:
                    self.state_handler(state='quit')
                    return False
        track = Track(
            title  = data['name'],
            album  = data['album'],
            artist = data['artist'],
            genre  = data['genre'],
            year   = data['year'],
            tracknumber = data['track-number'],
            cover  = self.get_cover_path(data['URI'])
        )
        
        return track
            
# ================================= HANDLERS ================================= #

    def playing_changed_handler(self, message,b=None,c=None):
        """
            Handles StatusChanged dbus signal, calls state_handler()
            
            @param message: string
        """
        self.state_handler(state=self.get_state(message))
            
    def song_changed_handler(self, message,b=None,c=None):
        """
            Handles TrackChanged dbus signal, calls state_handler()
            
            @param message: string
        """
        if message == 'startofstream':
            track = self.get_track()
            self.state_handler(track=track)
