# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# smytvshow
# Pusher for www.filmpertutti.click
# 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__ = "FilmPerTutti"


class FilmPerTutti():
    __object_type__ = "P"
    __object_name__ = "p_filmpertutti"

    def __init__(self):
        return

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

        item_list = []

        item_list.append(self.build_search_item(item))
        item_list.append(items.MenuItem(self, config.get_localized_string(30106), "last_episodes",
                                        extra={"url": "http://www.filmpertutti.click/ultime_serie"},
                                        thumbnail="[last]"))

        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 last_episodes(self, item):
        logger.debug("start...")
        plugin.set_content_to_tv_shows()

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

        data = scrapertools.cache_page(item_url)

        patron = '<div class="col-md-8">(.*?)<div class="col-md-4">'
        data1 = c.find_single_match(data, patron)+'<br />'

        patron = '<strong><a href="([^"]+)".*?>(.*?)</a>(.*?)<br />'
        matches = re.compile(patron,re.DOTALL).findall(data1)

        for url, title, full_plots in matches:
            title = c.normalize(title).lstrip().rstrip()
            url = "http://www.filmpertutti.click%s" % (url)

            patron = '<span [^>]+>(.*?)<'
            plots = re.compile(patron,re.DOTALL).findall(full_plots)

            full_plot = ''
            for dirty_plot in plots:
                full_plot = full_plot + "(%s) " % (dirty_plot)
            full_plot = full_plot.rstrip()

            si = items.ShowItem(self, item, 0, title, "list_seasons", {"url": url})

            if si.show_id <> 0:
                si.properties["plot"] = full_plot
                si.properties["plotoutline"] = full_plot
                item_list.append(si)

        gui.render_items(item_list, gui.def_view_last)

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

    def global_search(self, item):
        item.item_info["extra.url"] = "http://www.filmpertutti.click/search/%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.filmpertutti.click/search/%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 = '<a href="([^"]+)" rel="bookmark".*?' \
                 '<img .*?src="([^"]+).*?' \
                 '<h2>(.*?)</h2>.*?' \
                 '<p>(.*?)</p>.*?</a>'
        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 href="([^"]+)"[^>]+>Avanti</a>')
                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 = '<article(.*?)</article>'
        match = c.find_single_match(data, patron)
        patron = '<p><strong>(.*?)<'
        matches = re.compile(patron, re.IGNORECASE | re.DOTALL).findall(match)

        count_season = 0

        for match in matches:
            ori_match = match
            match = c.html_clean(ori_match.lower()).replace("\xc2\xa0"," ").rstrip().lstrip()
            if 'stagion' in match:
                subbed = False
                words = match.split(' ')

                if len(words) > 2:
                    for word in words:
                        if "sub" in word.lower():
                            subbed = True
                try:
                    if 'stagion' in words[0].lower():
                        season = int(words[1])
                    else:
                        season = c.ordinal.index(words[0].lower().strip())
                    count_season = season
                except Exception, e:
                    if len(words) > 0:
                        logger.error("The word [%s] has not been found in dictionary." % words[0].lower().strip())
                    else:
                        logger.error("No season title found!")
                    count_season += 1
                    season = count_season
                    pass

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

                if subbed:
                    si.properties["subbed"] = 1

                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"]
        html_season = item.item_info["extra.html_season"]
        show_id = int(item.item_info["show_id"])
        season = int(item.item_info["item_season"])
        item_list = []

        data = scrapertools.cache_page(item_url)
        if html_season == "##":
            patron = '<div class="entry-content">(.*?)<span class="clear"></span>'
            data = c.find_single_match(data, patron)
            patron = '<p>(.*?)</p>'
        else:
            patron = '<strong>' + html_season + '</strong></p>(.*?)</p>'

        matches = re.compile(patron, re.IGNORECASE | re.DOTALL).findall(data)

        for match in matches:
            patron = '<br />'
            episode_rows = re.compile(patron, re.IGNORECASE | re.DOTALL).split(match)
            for episode_row in episode_rows:
                episode_row = episode_row.replace('<p>', '', 1).lstrip().rstrip()
                patron = '(.*?)<a'
                dirty_title = c.find_single_match(episode_row, patron)
                if dirty_title:
                    title = c.normalize(dirty_title)
                    patron = 'x([0-9]+)'
                    try:
                        episode = int(c.find_single_match(title, patron))
                        ei = items.EpisodeItem(self, item, show_id, season, episode, title,
                                               "list_videos_run", {"url": item_url, "data": episode_row})

                        if (show_id == 0) | (season == 0):
                            ei.properties["title"] = config.get_localized_string(30902) % (str(episode))

                        item_list.append(ei)
                    except:
                        pass

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

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

        data = item.item_info["extra.data"]

        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)
