from __future__ import unicode_literals

import logging
import requests

from urlparse import urljoin

from mopidy_podcast.directory import PodcastDirectory
#from mopidy_podcast.models import Ref

SEARCH_PATH = '/search'

logger = logging.getLogger(__name__)


class gPodderDirectory(PodcastDirectory):

    name = 'gpodder'

    genre = None

    def __init__(self, backend):
        super(gPodderDirectory, self).__init__(backend)
        self.label = self.config['label']
        self.session = requests.Session()
        self.search_url = urljoin(self.config['base_url'], SEARCH_PATH)

    @property
    def config(self):
        return self.backend.config['podcast-gpodder']

    def browse(self, path):
        return []

    def search(self, terms=None, attribute=None):
        if not terms:
            return []
        return []

    def request(self, url, params=None):
        timeout = self.config['timeout']
        response = self.session.get(url, params=params, timeout=timeout)
        return response.json()

@@ -154,9 +154,8 @@
 ory%0A
-#
 from
@@ -189,16 +189,98 @@
 rt Ref%0A%0A
+TAG_PATH = '/api/2/tag/%7Btag%7D/%7Bcount%7D.json'%0ATAGS_PATH = '/api/2/tags/%7Bcount%7D.json'%0A
 SEARCH_P
@@ -293,16 +293,21 @@
 '/search
+.json
 '%0A%0Alogge
@@ -340,16 +340,613 @@
 me__)%0A%0A%0A
+def _to_directory_refs(results):%0A    refs = %5B%5D%0A    for result in results:%0A        try:%0A            refs.append(Ref.directory(uri=result%5B'tag'%5D, name=result%5B'tag'%5D))%0A        except Exception as e:%0A            logger.error('gPodder format error: %25r %25r', e, result)%0A    return refs%0A%0A%0Adef _to_podcast_refs(results):%0A    # TODO: try to filter duplicates%0A    refs = %5B%5D%0A    for result in results:%0A        try:%0A            refs.append(Ref.podcast(uri=result%5B'url'%5D, name=result%5B'title'%5D))%0A        except Exception as e:%0A            logger.error('gPodder format error: %25r %25r', e, result)%0A    return refs%0A%0A%0A
 class gP
@@ -1193,16 +1193,150 @@
 ssion()%0A
+        self.tag_url = urljoin(self.config%5B'base_url'%5D, TAG_PATH)%0A        self.tags_url = urljoin(self.config%5B'base_url'%5D, TAGS_PATH)%0A
         
@@ -1516,145 +1516,548 @@
 lf, 
-path):%0A        return %5B%5D%0A%0A    def search(self, terms=None, attribute=None):%0A        if not terms:%0A            return %5B%5D%0A        return %5B%5D
+tag):%0A        tag = tag.strip('/')%0A        if not tag:%0A            results = self.request(self.tags_url.format(count=10))%0A            return _to_directory_refs(results)%0A        else:%0A            results = self.request(self.tag_url.format(tag=tag, count=10))%0A            return _to_podcast_refs(results)%0A%0A    def search(self, terms=None, attribute=None):%0A        if not terms:%0A            return %5B%5D%0A        results = self.request(self.search_url, params=%7B%0A            'q': '+'.join(terms),%0A        %7D)%0A        return _to_podcast_refs(results)
 %0A%0A  

Implement browsing, searching.