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

"""
This metadata provider, looks if there is might a Cover (file) in of of the
cache files
"""


__maintainer__ = 'Benjamin Kampmann <benjamin@fluendo.com>'


from elisa.base_components.metadata_provider import MetadataProvider

import os

from twisted.internet import threads


class CoverCache(MetadataProvider):
    """
    This CoverCache Metadata Provider just looks if there is a cover in
    its cache which could fit to the used artist/album.

    @ivar list_of_extentions:   a list of extentions our cover could have
    @type list_of_extentions:   list
    """

    # lowercase only
    list_of_extentions = ['png', 'jpg', 'xpm', 'jpeg']

    config_doc = {'caches': 'the pathes to the caches of the covers'}

    default_config = {'caches': []}



    def initialize(self):
        """ we set some special things here """
        self._cached = {}
        self.renew_cache()

    def renew_cache(self):
        self._cached = {}
        for cache in self.config.get("caches", []):
            if not os.path.isdir(cache):
                self.warning("%s is not a directory" % cache)
                continue
            for eachfile in os.listdir(cache):
                if os.path.isdir(eachfile):
                    self.warning("Skipping %s: we don't look rekursiv!" %
                                                                eachfile)
                    continue

                if eachfile.find('.') == -1:
                    # we don't support files without extension
                    continue

                name, ext = eachfile.rsplit('.', 1)

                if ext.lower() in self.list_of_extentions:
                    name = name.lower().rstrip().lstrip()
                    filename = "%s/%s" % (cache, eachfile)

                    if self._cached.has_key(name):
                        self.warning("Skipping %s: already an entry for %s" %
                                      (filename, name))
                        continue

                    self._cached[name] = filename


    def get_rank(self):
        # metadata manager will look here first
        return 180

    def able_to_handle(self, metadata):
        if metadata.get('cover', None) != None:
            if metadata.get('default_image', '') != None:
                return False

        # at least artist or album is needed

        if metadata.get('album', None) != None and \
                        metadata.get('artist', None)!= None:
            return True

        return False

    def get_metadata(self, metadata, low_priority=False):
        d = threads.deferToThread(self._search_for_cover, metadata)
        return d


    def _search_for_cover(self, metadata):
        artist = metadata.get('artist', '').lower().strip()
        album =  metadata.get("album", '').lower().strip()

        search_list = ["%s-%s" % (artist, album),
                         "%s - %s" % (artist, album),
                         album]

        for search in search_list:
            if self._cached.get(search, None) != None:
                return self._set_cover(metadata, self._cached[search])

        return metadata


    def _set_cover(self, metadata, cover_path):
        if metadata.get('cover', None) == None:
            metadata['cover'] = cover_path

        # set image globally if not yet set
        if metadata.get('default_image', '') == None:
            metadata['default_image'] = cover_path

        return metadata



if __name__ == "__main__":

    from twisted.internet import reactor

    c = CoverCache()
    c.config = {'caches': ['/tmp/covers', '/tmp/amazon']}
    c.initialize()

    print "rank:",c.get_rank()
    print "Should be able to handle:", c.able_to_handle({'artist' :
    'gorillaz', 'album' : 'gorillaz'})
    print "Should not be able to handle:", c.able_to_handle({'uri' : ''})

    def start():

        def print_it(metadata):
            print "metadata is", metadata


        df = c.get_metadata({'artist': 'gorillaz', 'album' : 'gorillaz'})
        df.addCallback(print_it)


    reactor.callWhenRunning(start)

    reactor.run()
