# -*- 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__ = 'Florian Boucault <florian@fluendo.com>'
__maintainer2__ = 'Benjamin Kampmann <benjamin@fluendo.com>'

from elisa.core import common
from elisa.extern.log import log
from twisted.internet import defer, reactor, threads

class ThumbnailerError(Exception):
    pass

class Thumbnailer(log.Loggable):

    logCategory = "thumbnailer"

    def start(self):
        pass

    def stop(self):
        pass

    def get_thumbnail(self, uri, size, media_type):
        """
        Creates a thumbnail of uri on a local location.
        Returns a deferred, it's callback is called with
        a tuple containing the local filename of the thumbnail
        and its size as an int.
        Calls the deferred error callback if an error occured.

        @param uri:     URI to generate a thumbnail from
        @type uri:      L{elisa.core.media_uri.MediaUri}
        @param size:    size of the desired thumbnail
        @type size:     int
        @rtype:         L{twisted.internet.defer.Deferred}
        """
        
        metadata = {'uri': uri, 'thumbnail': None}

        def got_thumbnail(result):
            # if the gst_metadata provider fails the metadata manager skips the
            # error and goes on with the other providers so we get a callback
            # with thumbnail=None
            location = result['thumbnail']
            if location is None:
                raise ThumbnailerError()
            
            return (location, size)

        dfr = common.application.metadata_manager.get_metadata(metadata)
        dfr.addCallback(got_thumbnail)

        return dfr
