from xbmctorrentV2 import plugin
from xbmctorrentV2.scrapers import scraper
from xbmctorrentV2.ga import tracked
from xbmctorrentV2.caching import cached_route
from xbmctorrentV2.utils import ensure_fanart
from xbmctorrentV2.library import library_context


BASE_URL = "%s/" % plugin.get_setting("base_bitsnoop")
HEADERS = {
    "Referer": BASE_URL,
}
# Cache TTLs
DEFAULT_TTL = 24 * 3600 # 24 hours


@scraper("BitSnoop - Search Engine", "%s/i/logo.png" % BASE_URL)
@plugin.route("/bitsnoop")
@ensure_fanart
@tracked
def bitsnoop_index():
    plugin.redirect(plugin.url_for("bitsnoop_search"))


@plugin.route("/bitsnoop/browse/<root>/<page>")
@library_context
@ensure_fanart
@tracked
def bitsnoop_page(root, page):
    



@plugin.route("/bitsnoop/search")
@tracked
def bitsnoop_search():
    import urllib
    from xbmctorrentV2.utils import first

    query = plugin.request.args_dict.pop("query", None)
    if not query:
        query = plugin.keyboard("", "xbmctorrentV2 - Bitsnoop - Search")
    if query:
        plugin.redirect(plugin.url_for("bitsnoop_page", root="/search/video/%s/c/d/" % urllib.quote("%s safe:no" % query, safe=""), page=1, **plugin.request.args_dict))

from urlparse import urljoin
    from xbmctorrentV2.scrapers import rss
    from xbmctorrentV2.utils import url_get

    content_type = plugin.request.args_dict.get("content_type")
    if content_type:
        plugin.set_content(content_type)

    page = int(page)
    page_data = url_get(urljoin(BASE_URL, "%s/%d/" % (root, page)), headers=HEADERS, params={
        "fmt": "rss",
        "sort": "n_s",
        "dir": "desc",
    })
    return rss.parse(page_data)