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


class ExailePlayer(GenericPlayer):
    """
        Exaile 0.2.x player plugin
    """
    __name__ = 'Exaile'
    __version__ = '0.1'
    __author__ = 'Sterker <s.viilup@gmail.com>, Alexandr Grigorcea <cahr.gr@gmail.com>'
    __desc__ = 'API to the Exaile Music Player'
    
    DBUS_NAME   = 'org.exaile.DBusInterface'
    DBUS_OBJECT = '/DBusInterfaceObject'
    
    dbus_object = None
    timeout_id = 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.timeout_id:
            self.timeout_id = gobject.timeout_add(2000, self.check_new_song)
        return True

    def disconnect(self):
        """
            Disconnects player
        """
        if self.timeout_id:
            gobject.source_remove(self.timeout_id)

    def check_new_song(self):
        self.state_handler(state=self.get_state(), track=True)
        return True

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

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

    def get_rating(self):
        """
            @return: integer, [0-5] value, representing rating of current
                playing song
        """
        try:
            rating = self.dbus_object.get_track_attr('rating')
            return rating.count('*')
        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)
        """
        if not data:
            data = {}
            data['album'] = self.get_album()
            data['artist'] = self.get_artist()
        location = self.dbus_object.get_track_attr('loc')
        cover = self.search_cover(location,data,False)
        if cover:
            return cover
        try:
            cover = self.dbus_object.get_cover_path()
            if not "nocover.png" in cover:
                return cover
        except:
            pass
        return ''

    def get_state(self):
        """
            Returns players actual state.
            @return: string - playing, paused, stopped
        """
        return self.dbus_object.status()
        
    def is_playing(self):
        """
            @return: boolean, True if player is playing, False if not
        """
        try:
            if self.dbus_object.status() == "playing":
                return True
        except:
            pass
        return False

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

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

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

    def get_track(self):
        if self.get_state() == 'stopped':
            return Track()
        data = {}
        data['title'] = self.dbus_object.get_title()
        data['artist'] = self.dbus_object.get_artist()
        data['album'] = self.dbus_object.get_album()
        data['rating'] = self.get_rating()
        data['genre'] = self.dbus_object.get_track_attr('genre')
        data['tracknumber'] = self.dbus_object.get_track_attr('track')
        data['year'] = self.dbus_object.get_track_attr('year')
        data['cover'] = self.get_cover_path(data)
        
        track = Track(
            title  = data['title'],
            album  = data['album'],
            artist = data['artist'],
            genre  = data['genre'],
            year   = data['year'],
            tracknumber = data['tracknumber'],
            rating = data['rating'],
            cover  = data['cover']
        )
        return track
