import logging
import threading

from spotify.manager import SpotifySessionManager
from spotify.alsahelper import AlsaController

from mopidy import config
from mopidy.backends import BaseBackend

logger = logging.getLogger(u'backends.libspotify')

class LibspotifyBackend(BaseBackend):
    def __init__(self, *args, **kwargs):
        super(LibspotifyBackend, self).__init__(*args, **kwargs)
        logger.info(u'Connecting to Spotify')
        self.spotify = LibspotifySession(
            config.SPOTIFY_USERNAME, config.SPOTIFY_PASSWORD)
        self.spotify.start()


class LibspotifySession(SpotifySessionManager, threading.Thread):
    def __init__(self, *args, **kwargs):
        SpotifySessionManager.__init__(self, *args, **kwargs)
        threading.Thread.__init__(self)
        self.audio = AlsaController()
        self.queued = False

    def run(self):
        self.connect()

    def logged_in(self, session, error):
        logger.info('Logged in')
        try:
            self.playlists = session.playlist_container()
            logger.debug('Got playlist container')
        except Exception, e:
            logger.exception(e)

    def logged_out(self, session):
        logger.info('Logged out')

    def metadata_updated(self, session):
        logger.debug('Metadata updated')

    def connection_error(self, session, error):
        logger.error('Connection error: %s', error)

    def message_to_user(self, session, message):
        logger.info(message)

    def notify_main_thread(self, session):
        logger.debug('Notify main thread')

    def music_delivery(self, *args, **kwargs):
        self.audio.music_delivery(*args, **kwargs)

    def play_token_lost(self, session):
        logger.debug('Play token lost')

    def log_message(self, session, data):
        logger.debug(data)

    def end_of_track(self, session):
        logger.debug('End of track')

    def test(self):
        # XXX This should play the first song in your first playlist :-)
        playlist_no = 0
        track_no = 0
        try:
            if not self.queued:
                if len(self.playlists) > playlist_no:
                    playlist = self.playlists[playlist_no]
                    if playlist.is_loaded():
                        if playlist[track_no].is_loaded():
                            session.load(playlist[track_no])
                            session.play(1)
                            self.queued = True
                            logger.info('Playing "%s"',
                                playlist[track_no].name())
        except Exception, e:
            logger.exception(e)


@@ -1,12 +1,34 @@
+import datetime as dt%0A
 import loggi
@@ -210,16 +210,73 @@
 eBackend
+%0Afrom mopidy.models import Artist, Album, Track, Playlist
 %0A%0Alogger
@@ -321,16 +321,36 @@
 tify')%0A%0A
+ENCODING = 'utf-8'%0A%0A
 class Li
@@ -633,16 +633,30 @@
 PASSWORD
+, backend=self
 )%0A      
@@ -679,16 +679,1666 @@
 tart()%0A%0A
+    def update_stored_playlists(self, spotify_playlists):%0A        logger.info(u'Updating stored playlists')%0A        playlists = %5B%5D%0A        for spotify_playlist in spotify_playlists:%0A            playlists.append(self._to_mopidy_playlist(spotify_playlist))%0A        self._playlists = playlists%0A        logger.debug(u'Available playlists: %25s',%0A            u', '.join(%5Bu'%3C%25s%3E' %25 p.name for p in self._playlists%5D))%0A%0A# Model translation%0A%0A    def _to_mopidy_artist(self, spotify_artist):%0A        return Artist(%0A            uri=u'', # FIXME Not supported by pyspotify?%0A            name=spotify_artist.name().decode(ENCODING),%0A        )%0A%0A    def _to_mopidy_album(self, spotify_album):%0A        # TODO pyspotify got much more data on albums than this%0A        return Album(name=spotify_album.name().decode(ENCODING))%0A%0A    def _to_mopidy_track(self, spotify_track):%0A        return Track(%0A            uri=u'', # FIXME Not supported by pyspotify?%0A            title=spotify_track.name().decode(ENCODING),%0A            artists=%5Bself._to_mopidy_artist(a)%0A                for a in spotify_track.artists()%5D,%0A            album=self._to_mopidy_album(spotify_track.album()),%0A            track_no=spotify_track.index(),%0A            date=dt.date(spotify_track.album().year(), 1, 1),%0A            length=spotify_track.duration(),%0A            id=0, # FIXME need URI or something unique first%0A        )%0A%0A    def _to_mopidy_playlist(self, spotify_playlist):%0A        return Playlist(%0A            uri=u'', # FIXME Not supported by pyspotify?%0A            name=spotify_playlist.name().decode(ENCODING),%0A            tracks=%5Bself._to_mopidy_track(t) for t in spotify_playlist%5D,%0A        )%0A
 %0Aclass L
@@ -2415,39 +2415,51 @@
 nit__(self, 
-*args, **kwargs
+username, password, backend
 ):%0A        S
@@ -2494,31 +2494,34 @@
 _(self, 
-*args, **kwargs
+username, password
 )%0A      
@@ -2550,24 +2550,55 @@
 nit__(self)%0A
+        self.backend = backend%0A
         self
@@ -3104,16 +3104,77 @@
 pdated')
+%0A        self.backend.update_stored_playlists(self.playlists)
 %0A%0A    de

Add browsing of stored playlist to libspotify backend