# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# smytvshow
# Pusher for www.guardaserie.me
# http://smystero.dlinkddns.org/smytvwhow/
#------------------------------------------------------------

import re

from core import items
from core import scrapertools, servertools
from core import common as c

from p_util import utils

from xbmcutils import plugin, gui, logger, config

__class_name__ = "GuardaSerie"


class GuardaSerie():
    __object_type__ = "P"
    __object_name__ = "p_guardaserie"

    def __init__(self):
        return

    def main(self, item):
        logger.debug("start...")
        plugin.set_content_to_movies()

        item_list = []

        item_list.append(items.MenuItem(self, config.get_localized_string(30100), "search",
                                        folder=False, playable=False, thumbnail="[search]"))
        item_list.append(items.MenuItem(self, config.get_localized_string(30101), "list_categories",
                                        {"url": "http://www.guardaserie.news/lista-serie-tv-guardaserie/"},
                                        thumbnail="[category]"))

        item_list.extend(utils.get_fav_list(self, item))

        gui.render_items(item_list, gui.def_view_pusher_main)

        logger.debug("end...")
        return

    def build_search_item(self, item):
        return items.MenuItem(self, config.get_localized_string(30100), "search",
                                        folder=False, playable=False, thumbnail="[search]")

    def list_favorites(self, item):
        utils.list_favorites(self, item)

    def list_categories(self, item):
        logger.debug("start...")
        plugin.set_content_to_movies()

        item_url = item.item_info["extra.url"]
        item_list = []

        data = scrapertools.cache_page(item_url)

        patron = '<li><strong>Categoria:</strong> <a href="([^"]+)"[^>]+>([^<]+)</a>'
        matches = re.compile(patron, re.DOTALL).findall(data)

        for url, title in matches:

            title = c.normalize(title)
            mi = items.MenuItem(self, title, "list_series", {"url": url})
            item_list.append(mi)

        gui.render_items(item_list, gui.def_view_categories)

        logger.debug("end...")
        return

    def global_search(self, item):
        item.item_info["extra.url"] = "http://www.guardaserie.news/?s=%s" % item.item_info["extra.url"]
        item.item_info["action"] = "null"
        return self.fill_series(item, next_page = False)

    def search(self, item):
        logger.debug("start...")
        ok, text = gui.get_user_input("")
        if ok:
            item.item_info["extra.url"] = "http://www.guardaserie.news/?s=%s" % text
            item.item_info["action"] = "list_series"
            gui.update_url(item.build_url())

        logger.debug("end...")

    def fill_series(self, item, next_page = False):
        logger.debug("start...")

        item_url = item.item_info["extra.url"]
        item_list = []

        data = scrapertools.cache_page(item_url)
        patron = '<div class="search_post">[^<]+'
        patron += '<div class="search_thumbnail">[^<]+'
        patron += '<a class="search_link" href="([^"]+)"[^>]+'
        patron += '>[^<]+'
        patron += '<img src="([^"]+)" />[^<]+'
        patron += '</a>[^<]+'
        patron += '</div>[^<]+'
        patron += '<div class="info">[^<]+'
        patron += '<div class="search_title">[^<]+'
        patron += '<a class="search_link" [^>]+'
        patron += '>([^<]+)'
        patron += '</a>[^<]+'
        patron += '</div>[^<]+'
        patron += '<div class="short_info">'
        patron += '([^<]+)'
        patron += '<a [^>]+'
        patron += '><br>[^<]+</a>[^<]+'
        patron += '</div>[^<]+'
        patron += '</div>[^<]+'
        patron += '</div>'
        matches = re.compile(patron, re.DOTALL).findall(data)

        for url, thumbnail, title, plot in matches:
            title = c.normalize(title)
            si = items.ShowItem(self, item, 0, title, "list_seasons", {"url": url})
            if si.show_id == 0:
                si.properties["title"] = title
                si.properties["poster"] = thumbnail
                si.properties["plot"] = plot
                si.properties["plotoutline"] = plot
            item_list.append(si)

        if next_page:
            # Next Page
            try:
                next_page = c.get_match(data, '<a class="nextpostslink" [^h]+href="([^"]+)"')
                mi = items.MenuItem(self, config.get_localized_string(30102), "list_series", {"url": next_page})
                item_list.append(mi)
            except:
                pass

        logger.debug("end...")
        return item_list

    def fill_seasons(self, item):
        logger.debug("start...")

        item_url = item.item_info["extra.url"]
        show_id = int(item.item_info["show_id"])
        item_list = []

        data = scrapertools.cache_page(item_url)

        patron = '<l[^>]+><span>([^<]+)</span>'
        matches = re.compile(patron, re.DOTALL).findall(data)

        for match in matches:
            season = int(match)

            title = c.normalize(config.get_localized_string(30901) % str(season))
            si = items.SeasonItem(self, item, show_id, season, title, "list_episodes", {"url": item_url})

            if si.show_id == 0:
                si.properties["title"] = title

            item_list.append(si)

        logger.debug("end...")
        return item_list

    def fill_episodes(self, item):
        logger.debug("start...")

        item_url = item.item_info["extra.url"]
        show_id = int(item.item_info["show_id"])
        season = int(item.item_info["item_season"])
        item_list = []

        data = scrapertools.cache_page(item_url)

        patron = "<link rel='shortlink' href='[^=]+=([^']+)'"
        html_serie = c.find_single_match(data,patron)

        patron = '<l[^>]+><span>' + str(season) + '</span[^<]+<ul>(.*?)</ul>'
        html_season = c.find_single_match(data,patron)

        patron = '<l[^>]+>([^<]+)</li>'
        matches = re.compile(patron,re.DOTALL).findall(html_season)

        for match in matches:
            episode = int(match)

            title = c.normalize(config.get_localized_string(30902) % str(episode))
            url = 'http://www.guardaserie.news/wp-admin/admin-ajax.php'

            ei = items.EpisodeItem(self, item, show_id, season, episode, title, "list_videos_run",
                                   {"url": url,
                                    "html_serie": html_serie,
                                    "referrer": item_url})

            if show_id == 0:
                ei.properties["title"] = title

            item_list.append(ei)

        logger.debug("end...")
        return item_list

    def fill_videos(self, item):
        logger.debug("start...")

        season = int(item.item_info["item_season"])
        episode = int(item.item_info["item_episode"])

        item_url = item.item_info["extra.url"]
        item_serie = item.item_info["extra.html_serie"]
        item_referrer = item.item_info["extra.referrer"]

        post = "action=get_episode&id=%s&season=%s&episode=%s" % (item_serie, str(season-1), str(episode-1))

        headers = scrapertools.def_headers
        headers.append(['Referer', item_referrer])
        data = scrapertools.cache_page(item_url, post=post, headers=headers)

        item_list = servertools.list_videos(self, item, data)

        logger.debug("end...")
        return item_list

    def list_series(self, item):
        logger.debug("start...")
        plugin.set_content_to_tv_shows()

        item_list = self.fill_series(item, next_page = True)

        gui.render_items(item_list, gui.def_view_series)

        logger.debug("end...")
        return

    def list_seasons(self, item):
        logger.debug("start...")
        plugin.set_content_to_tv_shows()

        item_list = self.fill_seasons(item)

        gui.render_items(item_list, gui.def_view_seasons)

        logger.debug("end...")
        return

    def list_episodes(self, item):
        logger.debug("start...")
        plugin.set_content_to_tv_shows()

        item_list = self.fill_episodes(item)

        gui.render_items(item_list, gui.def_view_episodes)

        logger.debug("end...")
        return

    def list_videos(self, item):
        logger.debug("start...")
        plugin.set_content_to_tv_shows()

        item_list = self.fill_videos(item)
        utils.add_collect_item(item_list, item)

        gui.render_items(item_list, gui.def_view_videos)

        logger.debug("end...")
        return

    def show_urls(self, item):
        utils.show_urls(self, item)
