#!/usr/bin/env python

# Music Player Deamon

import os
import common
import gobject
import ConfigParser
try:
    import mpd
except ImportError:
    import sys
    message = common._("python-mpd is non installed.\nInstall it or run covergloobus-config to select another player.")
    common.c.error(message)
    sys.exit(1)
from GenericPlayer import GenericPlayer
from common import Track

class MPDPlayer(GenericPlayer):
    __name__ = 'Music Player Deamon'
    __version__ = '0.0'
    __author__ = 'Jaap Broekhuizen <jaapz.b@gmail.com>'
    __desc__ = 'API to the Music Player Deamon'
    
    client = mpd.MPDClient()
    timeout_id = None

    last_track = Track()

    def __init__(self, d=None):
        GenericPlayer.__init__(self,d)
        self.connect()

    def connect(self):
        if not self.timeout_id:
            common.c.debug('MPD: registering timeout')
            self.timeout_id = gobject.timeout_add(2000, self.check_new_song)
            return self._connect()
        else:
            common.c.debug('MPD: timeout already registered')
            return self.is_active()

    def _connect(self):
        try:
            if self.connected:
                common.c.debug('MPD: was connected, disconnecting')
                self.client.disconnect()
            common.c.debug('MPD: connecting')
            self.client.connect(self.config.get('MPD', 'host'),
                self.config.getint('MPD', 'port'))
            if self.config.get('MPD', 'password') != '':
                common.c.debug('MPD: using password')
                self.client.password(self.config.get('MPD', 'password'))
            self.connected = True
            common.c.debug('MPD: connection done')
            return True
        except:
            common.c.debug('MPD: connection failed')
            self.connected = False
            return False
   
    def disconnect(self):
        if self.connected:
            try:
                common.c.debug('MPD: disconnecting')
                self.client.disconnect()
            except:
                pass
            self.connected = False
        if self.timeout_id:
            self.state_handler(track='stopped')
            common.c.debug('MPD: removing timeout')
            gobject.source_remove(self.timeout_id)
            
    def check_new_song(self):
        self.state_handler(state=self.get_state(), track=True)
        return True
        
    def get_track(self):
        #common.c.debug('MPD: preparing track')
        data = self.client.currentsong()
        if self.last_track.title == data['title']:
            return self.last_track
        path = self.config.get('MPD', 'path')
        if path[-1:] != '/':
            path = path + '/'
        data['file'] = path + data['file']
        self.last_track = Track(
            title  = data['title'],
            album  = data['album'],
            artist = data['artist'],
            genre  = data['genre'],
            year   = data['date'],
            tracknumber = data['track'],
            cover = self.search_cover(data['file'],data))
        return self.last_track
        
    def is_active(self):
        try:
            self.client.status()
            return True
        except:
            common.c.debug('MPD: maybe not active, trying to reconnect')
            try:
                self._connect()
                self.client.status()
                return True
            except:
                pass
        return False
    
    def get_title(self):
        # Get title
        var = self.client.currentsong()
        if 'title' in var:
            title = str(var['title'])
            return title
        else:
            return ""
    
    def get_album(self):
        # Get Album
        var = self.client.currentsong()
        if 'album' in var:
            album = str(var['album'])
            return album
        else:
            return ""
        
    def get_artist(self):
        # Get Artist
        var = self.client.currentsong()
        if 'artist' in var:
            artist = str(var['artist'])
            return artist
        else:
            return ""

    def get_state(self):
        """
            Returns players actual state.
            @return: string - playing, paused, stopped
        """
        try:
            status = self.client.status()
        except:
            return 'stopped'
        if status['state'] == 'play':
            return 'playing'
        if status['state'] == 'pause':
            return 'paused'
        if status['state'] == 'stop':
            return 'stopped'
        
    def is_playing(self):
        # Is the player playing?
        status = self.client.status()
        if status['state'] == "play":
            return True
        else:
            return False
            
    def previous(self,widget,event):
        # Previous song
        if self.active:
            self.client.previous()
        
    def next(self,widget,event):
        # Next song
        if self.active:
            self.client.next()
        
    def play(self,widget,event):
        # Toggle play/pause
        if self.active:
            status = self.client.status()
            if status['state'] == "play":
                self.client.pause(1)
            else:
                self.client.pause(0)
