# -*- coding: utf-8 -*-
#------------------------------------------------------------
# smytvshow
# Main Menu Pusher
# http://smystero.dlinkddns.org/smytvwhow/
#------------------------------------------------------------

from core import items, runner, servertools

from xbmcutils import plugin, gui, logger, config
from xbmcutils import cache as plugin_cache

from tvdb import tvdb_api

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

__class_name__ = "MainMenu"

DEBUG = "N"

channels = {
    "p_italiafilm": ("ItaliaFilm.co", "P", "p_italiafilm", "")
    ,"p_altadefinizione": ("AltaDefinizione.club", "P", "p_altadefinizione", "")
    ,"p_guardaserie": ("GuardaSerie.news", "P", "p_guardaserie", "")
    ,"p_italiaserie": ("ItaliaSerie.news", "P", "p_italiaserie", "")
    ,"p_seriehd": ("SerieHD.org", "P", "p_seriehd", "")
    ,"p_filmpertutti": ("FilmPerTutti.click", "P", "p_filmpertutti", "")
}
channel_list = ("p_italiafilm","p_altadefinizione","p_guardaserie","p_italiaserie","p_seriehd","p_filmpertutti")

class MainMenu():

    __object_type__ = "M"
    __object_name__ = "main_menu"

    def __init__(self):
        return

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

        item_list = []

        if DEBUG == "S":
            item_list.append(items.MenuItem(self, "Test", "main", target_type="M", target="test_menu"))

        item_list.append(items.MenuItem(self, config.get_localized_string(30920), "pushers", thumbnail="[tv1]"))
        item_list.append(items.MenuItem(self, config.get_localized_string(30931), "search",
                                        folder=False, playable=False, thumbnail="[search]"))

        s = sql.SqlManager()

        rows = s.list_shows()
        if len(rows) > 0:
            if config.get_setting("favorites_apart") == "true":
                item_list.append(items.MenuItem(self, config.get_localized_string(30921), "list_favorites",
                                                thumbnail="[favorite]"))

            else:
                item_list.append(items.MenuItem(self, config.get_localized_string(30921), "null",
                                                folder=False, playable=False, thumbnail="[favorite]"))
                for row in rows:
                    item_list.append(items.ShowItem(self, None, row[0], row[1], "pusher_favorites"))

        if config.get_setting("show_advanced") == "true":
            item_list.append(items.MenuItem(self, config.get_localized_string(30922), "advanced", thumbnail="[advanced]"))

        gui.render_items(item_list, gui.def_view_main)

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

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

        item_list = []

        plugin.set_content_to_movies()

        item_list.append(items.MenuItem(self, config.get_localized_string(30924), "read_trakt",
                                        folder=False, playable=False, thumbnail="[advanced]"))
        item_list.append(items.MenuItem(self, config.get_localized_string(30923), "empty_cache",
                                        folder=False, playable=False, thumbnail="[advanced]"))
        item_list.append(items.MenuItem(self, config.get_localized_string(30929), "validate_cache",
                                        folder=False, playable=False, thumbnail="[advanced]"))

        gui.render_items(item_list)

        logger.debug("end...")

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

        if gui.yes_no_dialog(config.get_localized_string(30930), config.get_localized_string(30927)):
            c = plugin_cache.CacheManager()
            c.validate()
            del c

        gui.refresh()
        logger.debug("end...")

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

        if gui.yes_no_dialog(config.get_localized_string(30925), config.get_localized_string(30927)):
            c = plugin_cache.CacheManager()
            c.force()
            del c

        gui.refresh()
        logger.debug("end...")

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

        if gui.yes_no_dialog(config.get_localized_string(30926), config.get_localized_string(30927)):
            c = plugin_cache.CacheManager()
            c.clearTrakt()
            del c

        gui.refresh()
        logger.debug("end...")

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

        item_list = []
        count = 0
        #for k, channel in channels.items():
        for k in channel_list:
            channel = channels[k]
            count += 1
            item_list.append(items.MenuItem(self, config.get_localized_string(30928) % (count, channel[0]), "main", target_type=channel[1], target=channel[2]))

        gui.render_items(item_list, gui.def_view_pushers)

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

    def search(self, item):
        logger.debug("start...")
        ok, text = gui.get_user_input("")
        if ok:
            item.item_info["extra.searchtext"] = "%s" % text
            item.item_info["action"] = "list_series"
            gui.update_url(item.build_url())

        logger.debug("end...")

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

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

        item_list = []
        count = 0
        max_results = int(config.get_setting("max_result")) + 1
        inc = 100 / len(channel_list)
        progress = 0
        dlg = gui.progress_dialogBG(None, config.get_localized_string(30107) % searchtext)
        try:

            for k in channel_list:
                channel = channels[k]

                gui.progress_dialogBG(dlg, channel[0], progress)
                try:
                    search_item = runner.run_action(channel[1],channel[2],"build_search_item", runner.item_to_callerItem(item))
                    if search_item:
                        search_item.extra["url"] = searchtext
                        new_item_list = runner.run_action(channel[1],channel[2],"global_search", runner.item_to_callerItem(search_item))
                        if new_item_list:
                            if(len(new_item_list) > 0):
                                count += 1
                                item_list.append(items.MenuItem(self,
                                                                config.get_localized_string(30928) % (count, channel[0]),
                                                                "null",
                                                                target_type=channel[1], target=channel[2],
                                                                folder=False, playable=False))
                                conta_found = 0
                                for item_found in new_item_list:
                                    conta_found +=1
                                    if (conta_found < max_results):
                                        item_found.properties["title"] = ("  %s" %item_found.properties["title"])
                                        item_list.append(item_found)
                except Exception, e:
                    logger.error("Error [%s] during search in channel [%s]" % (e.message, channel[0]))
                    pass

                progress += inc
        finally:
            gui.progress_dialogBG(dlg, config.get_localized_string(30105), 100)
            pass

        gui.render_items(item_list, gui.def_view_series)

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

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

        item_list = []

        show_id = int(item.item_info["extra.show_id"])
        season = int(item.item_info["extra.season"])
        episode = int(item.item_info["extra.episode"])
        subbed = int(item.item_info["extra.subbed"])
        s = sql.SqlManager()
        try:
            count = 0
            rows = s.list_pushers_by_show(show_id)
            inc = 100 / len(rows)
            progress = 0
            dlg = gui.progress_dialogBG(None, config.get_localized_string(30932))
            try:
                for row in rows:
                    count += 1
                    found_in_channel = False
                    channel = channels[row[1]]
                    gui.progress_dialogBG(dlg, channel[0], progress)
                    try:
                        show_item = items.ShowItem(channel[1], item, show_id, "", row[3], items.url_decode(row[2]), row[4], row[5])
                        season_items = runner.run_action(channel[1],channel[2],"fill_seasons", runner.item_to_callerItem(show_item))
                        if season_items:
                            for season_item in season_items:
                                if (season_item.properties["season"] == season):
                                    if (season_item.properties["subbed"] == subbed):
                                        episode_items = runner.run_action(channel[1],channel[2],"fill_episodes", runner.item_to_callerItem(season_item))
                                        if episode_items:
                                            for episode_item in episode_items:
                                                if (episode_item.properties["episode"] == episode):
                                                    video_list = runner.run_action(channel[1],channel[2],"fill_videos", runner.item_to_callerItem(episode_item))
                                                    for item_found in video_list:
                                                        if not found_in_channel:
                                                            item_list.append(items.MenuItem(self,
                                                                config.get_localized_string(30928) % (count, channel[0]),
                                                                "null",
                                                                target_type=channel[1], target=channel[2],
                                                                folder=False, playable=False))
                                                            found_in_channel = True

                                                        item_found.from_search = True
                                                        item_list.append(item_found)
                    except Exception, e:
                        logger.error("Error [%s] during search for episode in channel [%s]" % (e.message, channel[0]))
                        pass
                    progress += inc
            finally:
                gui.progress_dialogBG(dlg, config.get_localized_string(30105), 100)
                pass

        finally:
            del s

        gui.render_items(item_list, gui.def_view_videos)

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

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

        item_list = []

        s = sql.SqlManager()

        rows = s.list_shows()
        if len(rows) > 0:
            inc = 100 / len(rows)
            progress = 0
            dlg = gui.progress_dialogBG(None, config.get_localized_string(30104))
            for row in rows:
                gui.progress_dialogBG(dlg, row[1], progress)
                item_list.append(items.ShowItem(self, None, row[0], row[1], "pusher_favorites"))
                progress += inc
            gui.progress_dialogBG(dlg, config.get_localized_string(30105), 100)
        gui.render_items(item_list, view_id=gui.def_view_favorites)

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

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

        item_fanart = item.item_info["fanart"]
        show_id = int(item.item_info["show_id"])
        item_list = []

        s = sql.SqlManager()

        rows = s.list_pushers_by_show(show_id)
        for row in rows:
            channel = channels[row[1]]
            extra = {"show_id":show_id, "url": row[2], "action": row[3], "target_type":row[4], "target": row[5]}
            item_list.append(items.MenuItem(self, config.get_localized_string(30916) % channel[0], "jump_to_fav",
                                            extra=extra, fanart=item_fanart, folder=False, playable=False))

        gui.render_items(item_list, gui.def_view_pushers)

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

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

        item_show_id = int(item.item_info["extra.show_id"])
        item_url = item.item_info["extra.url"]
        item_action = item.item_info["extra.action"]
        item_target_type = item.item_info["extra.target_type"]
        item_target = item.item_info["extra.target"]

        run_item = items.ShowItem(self, item, item_show_id, '', item_action,
                                  items.url_decode(item_url), item_target_type, item_target)
        gui.update_url(run_item.build_url())

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

        options = []
        id = []
        titles = []
        original_title = ""

        title = item.item_info["extra.title"]
        pusher = item.item_info["extra.pusher"]
        url = item.item_info["extra.url"]
        action = item.item_info["extra.action"]
        target_type = item.item_info["extra.target_type"]
        target = item.item_info["extra.target"]

        ok, text = gui.get_user_input(title)
        if ok:
            tv_db = tvdb_api.TvDb()
            search_results = tv_db.search(text)
            for result in search_results:
                real_title = "%s - %s (%s)" % (str(result["id"]), result["seriesname"], result["language"])
                options.append(real_title)
                id.append(result["id"])
                titles.append(result["seriesname"])

            if len(options) > 0:
                choice = gui.show_select_dialog(config.get_localized_string(30911),options)
                if choice >= 0:
                    original_title = tv_db.get_original_title(id[choice])
                    import hashlib
                    m = hashlib.md5()
                    m.update(title)
                    digest = m.hexdigest()
                    s = sql.SqlManager()
                    s.add_show(id[choice], titles[choice], original_title, pusher, digest, url, action, target_type, target)
                    gui.refresh()
            else:
                gui.error_dialog(config.get_localized_string(30913))


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

    def rem_from_fav(self, item):
        logger.debug("start...")
        if gui.yes_no_dialog(config.get_localized_string(30914), config.get_localized_string(30915)):
            show_id = int(item.item_info["extra.show_id"])
            pusher = item.item_info["extra.pusher"]

            s = sql.SqlManager()
            if not s.remove_show(pusher, show_id):
                gui.error_dialog(config.get_localized_string(30913))

            gui.refresh()

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

