# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2006-2009 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: Philippe Normand <philippe@fluendo.com>

from elisa.plugins.search.searcher import Searcher
from elisa.core import media_uri
from elisa.core.utils import defer

from elisa.core.resource_manager import  ResourceProviderNotFound
from elisa.plugins.poblesec.search_controller import SearcherEntry


class YoutubeSearcher(Searcher):
    """
    This is the Searcher for youtube. It currently supports only video
    searches. Filters are ignored.
    """
    paths = ['videos']
    provider_path = "elisa.plugins.youtube.resource_provider:"\
                    "YoutubeResourceProvider"
    base_path = "http://gdata.youtube.com/feeds/api/videos?vq=%s" \
                "&max-results=50" 

    def search(self, uri, model):
        provider = self._query_provider()
        if provider is None:
            return defer.fail(ResourceProviderNotFound(self.provider_path))

        def got_videos(result_model):
            model.videos = result_model.videos
            return model

        query_string = uri.filename
        encoded_query_string = media_uri.quote(query_string)
        search_uri = media_uri.MediaUri(self.base_path % encoded_query_string)
        result_model, dfr = provider.get(search_uri)
        dfr.addCallback(got_videos)
        return dfr


def video_search_result_decorator(controller):
    searcher = 'YoutubeSearcher'
    title = 'Youtube Search Results'
    searcher_entry = SearcherEntry(searcher, title, None)
    controller.searchers.append(searcher_entry)
    return defer.succeed(None)
