# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.

import gdata.photos, gdata.photos.service
#import pdb; pdb.set_trace()
        
class PicasaClient:

    def __init__(self, username, password):
        self._pws = gdata.photos.service.PhotosService()
        self._pws.ClientLogin(username, password)

    def _get_photos_feed(self, feed_type):
        feed = self._pws.GetUserFeed(kind=feed_type).entry
        photo_feed = dict([ (a.id.text, a.title.text) for a in feed ])
        return photo_feed

    def _get_photos_from_entry(self, entry):
        photos = {}
        for photo in entry:
            #summary = photo.summary.text
            title = photo.title.text
            thumbnails = [ (t.width, t.height, t.url)
                           for t in photo.media.thumbnail]
            thumbnails = dict([((int(t.width), int(t.height)), t.url)
                               for t in photo.media.thumbnail])
            keys = thumbnails.keys()
            keys.sort()
            thumbnail = thumbnails[keys[-1]]
            photo_id = photo.id.text
            photos[photo_id] = (title, thumbnail)
            
        return photos

    def get_albums(self):
        return self._get_photos_feed('album')

    def get_tags(self):
        return self._get_photos_feed('tag')
        
    def get_photos_for_album_with_id(self, album_id):
        data = self._pws.Get(album_id).ToString()
        album = gdata.photos.AlbumEntryFromString(data)
        album_photos = self._pws.GetFeed(album.GetPhotosUri()).entry
        return self._get_photos_from_entry(album_photos)

    def get_photos_for_tag_with_id(self, tag_id):
        data = self._pws.Get(album_id).ToString()
        tag = gdata.photos.TagEntryFromString(data)
        tag_photos = self._pws.GetFeed(tag.GetTagssUri()).entry
        return self._get_photos_from_entry(tag_photos)
    
    def get_photo_url(self, photo_id):
        data = self._pws.Get(photo_id).ToString()
        photo = gdata.photos.PhotoEntryFromString(data)
        return photo.media.content[0].url
                
if __name__ == '__main__':
    clt = PicasaClient('', '')
    albums =  clt.get_albums()

    first = albums.keys()[0]
    
    photos = clt.get_photos_for_album_with_id(first)

    first_photo = photos.keys()[0]
    print clt.get_photo_url(first_photo)
