# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# smytvshow
# Pusher for www.italia-film.co
# 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

if config.use_mysql:
    from mysqlinterface import sql_manager as sql
else:
    from sql import sql_manager as sql

__class_name__ = "ItaliaFilm"


class ItaliaFilm():
    __object_type__ = "P"
    __object_name__ = "p_italiafilm"

    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.italia-film.co/ultimi-telefilm-streaming/"},
                                        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 = '<ul class="last_series">(.*?)</ul>'
        data1 = c.find_single_match(data, patron)
        patron = '<span class="tvseries_name">([^<]+)</span>[^<]+<a href="([^"]+)"[^>]+>' \
                 '<i class="icon-link"></i>([^<]+)<'
        matches = re.compile(patron,re.DOTALL).findall(data1)

        for title, url, 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["plot"] = plot
                si.properties["plotoutline"] = plot
                item_list.append(si)

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

        gui.render_items(item_list, gui.def_view_last)

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

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

        logger.debug("end...")

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

    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 = '<article(.*?)</article>'
        matches = re.compile(patron,re.DOTALL).findall(data)

        for match in matches:
            title = c.normalize(c.find_single_match(match,'<h3[^<]+<a href="[^"]+"[^<]+>([^<]+)</a>'))
            url = c.find_single_match(match,'<h3[^<]+<a href="([^"]+)"')
            plot = c.find_single_match(match,'<p class="summary">(.*?)</p>')
            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="next page-numbers" 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 = '([^<]+stagione[^<]*)<'
        matches = re.compile(patron, re.IGNORECASE | re.DOTALL).findall(c.find_single_match(data,'(.*?)<footer'))

        count_season = 0

        for match in matches:
            ori_match = '<'+match
            match = c.html_clean(ori_match.lower()).lower()
            if 'stagione' in match:
                subbed = False
                words = match.split(' ')

                if len(words) > 2:
                    if "sub" in words[2].lower():
                        subbed = True

                try:
                    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 = re.escape(html_season)+'.*?</p>(.*?)</p>'
        '''

        patron = re.escape(html_season)+'.*?</p>(.*?)</p>'

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

        count_episodes = 0
        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)
                if episode_row.lstrip().startswith('<'):
                    patron = '<a [^>]+>(.*?)</a>'
                else:
                    patron = '([^-]+)-'

                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))
                        count_episodes = episode
                    except:
                        count_episodes += 1
                        episode = count_episodes

                    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"] = title

                    item_list.append(ei)

        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)
