# 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 dbus, gtk, os, urllib, re
from gtk import gdk

class GenericPlayer:
    """
    This class has the basic functions for the player,
    There are some of them that must be implemented for each SpecificPlayer,
    Please, take a look at BansheePlayer.py for an example.
    All Players must extend this class.
    """
    __name__         = 'GenericPlayer'
    __version__     = '0.1'
    __author__         = 'BadChoice (guitarboy000@gmail.com), Alexandr Grigorcea <cahr.gr@gmail.com>'
    __desc__         = 'A Generic API to a Music Player. All Players must extend this'
    
    ## This variable will be used to store the name of the playing song 
    ## <br><b>It has to be updated in the specificPlayer class </b>
    last_song = ""
    
    active = False
    connected = False
    
    # State handler callback, called when player is started, closed,
    # playing, paused or stopped.
    state_handler = None

    config = None
    
    # main D-Bus interface object
    dbus = None
    
    DBUS_NAME = None
    DBUS_OBJECT = None

    _last_cover = None
    _last_dirname = None
    
    def __init__(self, d=None):
        """
            Initializes class, begins dbus listening if DBUS_NAME is provided
            @param d: dbus.Interface
        """
        if d:
            self.dbus = d
        if self.DBUS_NAME:
            dbus.SessionBus().add_signal_receiver(self._dbus_handler, 
                "NameOwnerChanged", 'org.freedesktop.DBus', 
                None, '/org/freedesktop/DBus')
                
    def _dbus_handler(self, name, a=None, b=None):
        """
            Callback recieves dbus signal NameOwnerChanged, controls senders
            name and if required calls state_handler with opropriate state.
        """
        if name == self.DBUS_NAME and self.state_handler:
            if self.is_active():
                self.state_handler(state='started')
            else:
                self.state_handler(state='closed')
    
    def close(self):
        """
            Disconnects player and stops listening dbus for NameOwnerChanged
            signal.
        """
        self.disconnect()
        if self.DBUS_NAME:
            dbus.SessionBus().remove_signal_receiver(self._dbus_handler, 
                "NameOwnerChanged", 'org.freedesktop.DBus', 
                None, '/org/freedesktop/DBus')
    
    def set_handler(self, handler):
        """
            Sets state_handler callback, called by CoverGloobus class when
            new player is loaded.
        """
        self.state_handler = handler

    def set_config(self, config):
        """
            Sets pointer to current CoverGloobus configuration
        """
        self.config = config
        
    def search_cover(self, filename=False, data=False,unquote=True):
        """
            Generic cover searcher
            
            @param filename: string, path of current playing song.
            @param data: dictionary, info about current playing song, 
                should contain 'artist' and 'album' keys.
            @param unquote: boolean, True if filename is in percent_encoded
                format.
        """
        if filename:
            if filename[:7] == 'file://':
                filename = filename[7:]
            if unquote:
                filename = urllib.unquote(filename.encode('utf-8'))
            dirname = os.path.dirname(filename)
            if dirname == self._last_dirname:
                return self._last_cover
            add = ''
            try:
                add = '|{0} - {1}'.format(data['artist'], data['album'])
            except:
                pass
            pattern = '^(folder|cover|front|album|albumart{0})\.(jpg|jpeg|png|gif)$'.format(add)
            reg = re.compile(pattern, re.I)
            for file in os.listdir(dirname):
                if reg.match(file):
                    self._last_cover = dirname + '/' + file
                    return self._last_cover
        if data:
            pass
        return ''

    #def web_search_cover(self, data):
    #    if self.config.getboolean("AmazonCovers", "value"):
    #        g.debug("Try to download cover")
    #        cover = WEBServices.amazon_download_cover(data['artist'],
    #                self.track.album, g)
	#			else:
	#				g.debug("No download (in config)")
	#				self.track.cover = ""
        
    def get_player_name(self):
        """
            Return players name
        """
        return self.__name__
    
# ============================== ABSTRACT PART =============================== #
    
    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
        """
        pass
    
    def is_active(self):
        """
            @return: boolean, True if player is running, False if not
        """
        pass
    
    def connect(self):
        """
            Connects player
            @return: boolean, True if successful, False if not
        """
        pass
        
    def disconnect(self):
        """
            Disconnects player
        """
        pass
    
    def get_title(self):
        """
            @return: string, title of current playing song
        """
        pass
    
    def get_album(self):
        """
            @return: string, album name of current playing song
        """
        pass
    
    def get_artist(self):
        """
            @return: string, artist name of current playing song
        """
        pass
    
    def get_rating(self):
        """
            @return: integer, [0-5] value, representing rating of current
                playing song
        """
        return ''

    def get_cover_path(self):
        """
            @return: string, path to the album art image of current playing
                songm, (not URI)
        """
        return ''

    def get_state(self):
        """
            Returns players actual state.
            @return: string - playing, paused, stopped
        """
        pass

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

    def previous(self ,widget, event):
        """
            Changes song to previous
        """
        pass

    def play(self ,widget, event):
        """
            Plays or pauses the player
        """
        pass  

    def next(self ,widget, event):
        """
            Changes song to next
        """
        pass
    
