# 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 Amarok2Player(GenericPlayer):
    """
        Amarok 2.x player plugin
    """
    __name__ = 'Amarok2'
    __version__ = '0.1'
    __author__ = 'Jaap Broekhuizen <jaapz.b@gmail.com>, Alexandr Grigorcea <cahr.gr@gmail.com>'
    __desc__ = 'API to Amarok2'
    
    DBUS_NAME   = 'org.kde.amarok'
    DBUS_OBJECT = '/Player'
    
    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
        """
        session_bus = dbus.SessionBus()
        self.dbus_object = session_bus.get_object(self.DBUS_NAME, 
            self.DBUS_OBJECT)
        if not self.connected:
            session_bus.add_signal_receiver(self.playing_changed_handler, 
                "StatusChange", 'org.freedesktop.MediaPlayer', 
                'org.mpris.amarok', '/Player')
            session_bus.add_signal_receiver(self.song_changed_handler, 
                "TrackChange", 'org.freedesktop.MediaPlayer', 
                'org.mpris.amarok', '/Player')
            self.connected = True
        return True
            
    def disconnect(self):
        """
            Disconnects player
        """
        if self.connected:
            session_bus = dbus.SessionBus()
            session_bus.remove_signal_receiver(self.playing_changed_handler, 
                "StatusChange", 'org.freedesktop.MediaPlayer', 
                'org.mpris.amarok', '/Player')
            session_bus.remove_signal_receiver(self.song_changed_handler, 
                "TrackChange", 'org.freedesktop.MediaPlayer', 
                'org.mpris.amarok', '/Player')
            self.connected = False
    
    def get_title(self):
        """
            @return: string, title of current playing song
        """
        try: 
            return self.dbus_object.GetMetadata()['title']
        except:
            return ''

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

    def get_rating(self):
        """
            @return: integer, [0-5] value, representing rating of current
                playing song
        """
        try: 
            return self.dbus_object.GetMetadata()['rating']
        except:
            return 0
            
    def get_cover_path(self, data=None):
        """
            @param data: dictionary, contains info about current playing song.
                optional
            @return: string, path to the album art image of current playing
                songm, (not URI)
        """
        cover = None
        if data:
            try:
                cover = data['arturl']
            except:
                pass
        if not cover:
            try:
                cover = self.dbus_object.GetMetadata()['arturl']
            except:
                pass
        if cover:
            cover = cover[7:]
            cover = urllib.unquote(cover.encode('utf-8'))
            return cover
        if data:
            try:
                cover = self.search_cover(data['location'], data)
                if cover:
                    return cover
            except:
                pass
        return ''

    def get_state(self, data=None):
        """
            Returns players actual state.
            @return: string - playing, paused, stopped
        """
        if not data:
            data = self.dbus_object.GetStatus()
        if data[0] == 0:
            return 'playing'
        if data[0] == 1:
            return 'paused'
        if data[0] == 2:
            return 'stopped'
        
    def is_playing(self):
        """
            @return: boolean, True if player is playing, False if not
        """
        data = self.dbus_object.GetStatus()
        if data[0] == 0:
            return True
        else:
            return False

    def previous(self, widget, event):
        """
            Changes song to previous
        """
        if self.active:
            self.dbus_object.Prev()

    def play(self, widget, event):
        """
            Plays or pauses the player
        """
        if self.active:
            self.dbus_object.Pause()

    def next(self, widget, event):
        """
            Changes song to next
        """
        if self.active:
            self.dbus_object.Next()
        
    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.GetMetadata()
        
        track = Track(
            title  = data['title'],
            album  = data['album'],
            artist = data['artist'],
            rating = data['rating'],
            genre  = data['genre'],
            year   = data['year'],
            tracknumber = data['tracknumber'],
            cover  = self.get_cover_path(data)
        )
        return track

# ================================= HANDLERS ================================= #

    def playing_changed_handler(self, message):
        """
            Handles StatusChanged dbus signal, calls state_handler()
            
            @param message: list
        """
        self.state_handler(state=self.get_state(message))
            
    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)
