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

import re
import binascii

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

from p_util import utils
from util import jsunescape

from xbmcutils import plugin, gui, logger, config

__class_name__ = "SerieHD"


class SerieHD():
    __object_type__ = "P"
    __object_name__ = "p_seriehd"

    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.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 global_search(self, item):
        item.item_info["extra.url"] = "http://www.seriehd.org/?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.seriehd.org/?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="imagen">(.*?)</div>'
        matches = re.compile(patron,re.DOTALL).findall(data)

        for match in matches:
            title = c.normalize(c.find_single_match(match,'<span class="cp\-title">(.*?)</span>'))
            url = c.find_single_match(match,'<A HREF="([^"]+)"')
            plot = title
            thumbnail = c.find_single_match(match,'<img src="([^"]+)"')
            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=\'previouspostslink\'.*?href=\'([^\']+)\'.*?Siguiente')
                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 = '<option data-stagione="([^"]+)"[^>]+>*.?</option>'
        matches = re.compile(patron, re.DOTALL).findall(data)

        for match in matches:
            season = int(match) + 1

            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 = '<form method="post" action="([^"]+)" id="chooseVid">'
        url = c.find_single_match(data,patron)

        patron = '<div class="list [a-z][a-z][a-z][a-z]Ep" data-stagione="' + str(season - 1) + '">(.*?)</div>'
        html_season = c.find_single_match(data,patron)

        patron = '<option.*?data-id="[^"]+" value="([^"]+)">.*?</option>'
        matches = re.compile(patron,re.DOTALL).findall(html_season)

        for match in matches:
            episode = int(match) + 1

            title = c.normalize(config.get_localized_string(30902) % str(episode))

            ei = items.EpisodeItem(self, item, show_id, season, episode, title, "list_videos_run",
                                   {"url": url,
                                    "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_referrer = item.item_info["extra.referrer"]

        post = "st_num=%s&pt_num=%s" % (str(season-1), str(episode-1))

        data = scrapertools.cache_page(item_url, post=post)

        patron = '<iframe id="iframeVid" width="100%" height="500px" src="([^"]+)" allowfullscreen></iframe>'
        url = c.find_single_match(data,patron)

        if 'hdpass.link' in url:
            headers = scrapertools.def_headers
            headers.append(['Referer', item_referrer])
            data = scrapertools.cache_page(url, headers=headers)

            start = data.find('<ul id="mirrors">')
            end = data.find('</ul>', start)
            data = data[start:end]

            patron = '<form method="get" action="">\s*'
            patron += '<input type="hidden" name="([^"]+)" value="([^"]+)"/>\s*'
            patron += '<input type="hidden" name="([^"]+)" value="([^"]+)"/>\s*'
            patron += '(?:<input type="hidden" name="([^"]+)" value="([^"]+)"/>\s*)?'
            patron += '<input type="submit" class="[^"]*" name="([^"]+)" value="([^"]+)"/>\s*'
            patron += '</form>'

            html = []
            for name1, val1, name2, val2, name3, val3, name4, val4 in re.compile(patron).findall(data):
                if name3 == '' and val3 == '':
                    get_data = '%s=%s&%s=%s&%s=%s' % (name1, val1, name2, val2, name4, val4)
                else:
                    get_data = '%s=%s&%s=%s&%s=%s&%s=%s' % (name1, val1, name2, val2, name3, val3, name4, val4)
                tmp_data = scrapertools.cache_page('http://hdpass.link/film.php?randid=0&' + get_data, headers=headers)

                patron = r'; eval\(unescape\("(.*?)",(\[".*?;"\]),(\[".*?\])\)\);'
                [(par1, par2, par3)] = re.compile(patron, re.DOTALL).findall(tmp_data)
                par2 = eval(par2, {'__builtins__': None}, {})
                par3 = eval(par3, {'__builtins__': None}, {})
                tmp_data = jsunescape.unescape(par1, par2, par3)
                if 'Google' in get_data:
                    tmp_data = c.find_single_match(tmp_data, r'tvar Data = \\"([^\\]+)\\";')
                    tmp_data = binascii.unhexlify(tmp_data)
                html.append(tmp_data.replace(r'\/', '/'))
            url = ''.join(html)
        item_list = servertools.list_videos(self, item, url)

        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)
