# -*- 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.

__maintainer__ = 'Philippe Normand <philippe@fluendo.com>'

from elisa.base_components.media_provider import MediaProvider, UriNotMonitorable
from elisa.core.media_uri import MediaUri
from elisa.core import common
from elisa.core.observers.dict import DictObservable
from twisted.internet import defer, threads

import picasa_client

from elisa.extern.translation import gettexter, N_
T_ = gettexter('elisa-picasa')

class PicasaMedia(MediaProvider):
    """
    """
    default_config = {'username': '',
                      'password': ''}

    config_doc = {'username': 'Your Picasa username',
                  'password': 'Your password (needed to access private content)',
                  }
        
    def initialize(self):
        username = self.config.get('username', '')
        password = self.config.get('password', '')
        self._client = picasa_client.PicasaClient(username, password)
        
        plugin_registry = common.application.plugin_registry
        InternetLocationMessage = plugin_registry.get_component_class('base:internet_location_message')
        
        uri = "picasa:///"
        action_type = InternetLocationMessage.ActionType.LOCATION_ADDED
        msg = InternetLocationMessage(action_type, "Picasa", 'picasa', uri,
                                      media_types=['image',],
                                      theme_icon='picasa')
        common.application.bus.send_message(msg)
        self.debug("Initialize done")
        
    def scannable_uri_schemes__get(self):
        return {}
    
    def supported_uri_schemes__get(self):
        return { 'picasa': 0 }

    def get_media_type(self, uri):
        dfr = defer.Deferred()
        if self._is_directory(uri):
            dfr.callback({'file_type': 'directory', 'mime_type': ''})
        else:
            # XXX: don't hardcode
            dfr.callback({'file_type': 'image', 'mime_type': 'image/jpeg'})
        return dfr

    def is_directory(self, uri):
        d = defer.Deferred()
        d.callback(self._is_directory(uri))
        return d

    def _is_directory(self, uri):
        return uri.scheme == 'picasa' and uri.host != 'photo'

    def get_real_uri(self, uri):
        real_uri = None
        if uri.path[1:]:
            photo_id = "http%s" % uri.path[1:]
            real_uri = MediaUri(self._client.get_photo_url(photo_id))
        return real_uri

    def has_children_with_types(self, uri, media_types):
        dfr = defer.Deferred()
        
        has_children = False
        if self._is_directory(uri):
            if 'image' in media_types:
                has_children = True

        dfr.callback(has_children)
        return dfr

    def _build_main_menu(self, children):
        self.debug("Building main menu")
        
        child_uri = MediaUri('picasa://albums')
        child_uri.label = T_(N_("My albums"))
        children.append((child_uri, {}))

        child_uri = MediaUri('picasa://tags')
        child_uri.label = T_(N_("My tags"))
        children.append((child_uri, {}))
        
        return children
        
    def _retrieve_children(self, uri, children):
        photos = {}
        tags = {}
        albums = {}
        
        host = uri.host
        if host == '':
            children = self._build_main_menu(children)            
        elif host == 'albums':
            albums = self._client.get_albums()
        elif host == 'tags':
            tags = self._client.get_tags()
        elif host == 'album':
            album_id = uri.path[1:] # strip / from path
            album_id = "http%s" % album_id
            photos = self._client.get_photos_for_album_with_id(album_id)
        elif host == 'tag':
            tag_id = uri.path[1:] # strip / from path
            tag_id = "http%s" % album_id
            photos = self._client.get_photos_for_tag_with_id(tag_id)
            
        for album_id, label in albums.iteritems():
            album_id = MediaUri(album_id)
            album_id.scheme = ""
            child_uri = MediaUri('picasa://album/%s' % album_id)
            child_uri.label = label
            children.append((child_uri, {}))
            
        for tag_id, label in tags.iteritems():
            tag_id = MediaUri(tag_id)
            tag_id.scheme = ""
            child_uri = MediaUri('picasa://tag/%s' % tag_id)
            child_uri.label = label
            children.append((child_uri, {}))

        for photo_id, (label, thumbnail_url) in photos.iteritems():
            photo_id = MediaUri(photo_id)
            photo_id.scheme = ""
            child_uri = MediaUri('picasa://photo/%s' % photo_id)
            child_uri.label = label
            metadata = DictObservable()
            metadata['default_image'] = MediaUri(thumbnail_url)
            children.append((child_uri, metadata))
                
        return children

    def get_direct_children(self, uri, l):
        d = threads.deferToThread(self._retrieve_children, uri, l)
        return d

    def _blocking_open(self, uri, mode=None):
        return None

    def uri_is_monitorable(self, uri):
        return False
