# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 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 Moovida with Fluendo's plugins.
#
# The GPL part of Moovida is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Moovida" in the root directory of this distribution package
# for details on that license.
#
# Author: Olivier Tilloy <olivier@fluendo.com>
#         Benjamin Kampmann <benjamin@fluendo.com>

"""
Retrieve Music Album Covers using the Amazon Resource Provider
"""

from elisa.core.components.metadata_capability import MetadataCapability
from elisa.core.resource_manager import ResourceProviderNotFound

from elisa.core import common
from elisa.core import media_uri
from elisa.plugins.base.models.audio import AlbumModel

from elisa.plugins.amazon.resource_provider import AWS_SERVER
from elisa.plugins.amazon.key import AWS_KEY

from twisted.internet import defer

from xml.dom import minidom


class AmazonCovers(MetadataCapability):

    rank = 10
    provider_path = 'elisa.plugins.amazon.resource_provider:AmazonResourceProvider'
    provider = None

    def able_to_handle(self, model):
        try:
            if isinstance(model, AlbumModel) and (model.artist or model.album):
                return True
        except AttributeError:
            return False
        return False

    def get_metadata(self, model):
        if self.provider is None:
            try:
                resource_manager = common.application.resource_manager
                self.provider = resource_manager.get_resource_provider_by_path(self.provider_path)
            except ResourceProviderNotFound, error:
                return defer.fail(error)

        base_query = 'http://' + AWS_SERVER + '/onca/xml?'
        service = 'Service=AWSECommerceService'
        access_key = '&AWSAccessKeyId=%s' % AWS_KEY
        operation = '&Operation=ItemSearch&SearchIndex=Music'
        response = '&ResponseGroup=Images'
        query = ''

        if  model.artist:
            query += '&Artist=%s' % media_uri.quote(model.artist.lower().strip())

        if model.album:
            query += '&Title=%s' % media_uri.quote(model.album.lower().strip())

        full_query = base_query + service + access_key + operation + \
                     response + query

        def request_done(response_model):
            if not response_model or not len(response_model.items):
                return model

            for item in response_model.items:
                if hasattr(item,'image') and item.image:
                    # find an image!
                    model.cover = item.image
                    break

            return model

        uri = media_uri.MediaUri(full_query)
        response_model, get_dfr = self.provider.get(uri)
        get_dfr.addCallback(request_done)
        return get_dfr
