# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# smytvshow
# Tools for streaming servers
# http://smystero.dlinkddns.org/smytvwhow/
# ------------------------------------------------------------

import re, sys

from xbmcutils import config, logger, gui
import scrapertools
from core import items, common as c

FREE_SERVERS = []
FREE_SERVERS.extend(['fastvideo', 'flashx', 'googlevideo', 'hdload', 'junkyvideo', 'movshare'])  # ,'putlocker'
FREE_SERVERS.extend(['novamov', 'nowvideo', 'rapidvideo', 'streaminto', 'backin'])
FREE_SERVERS.extend(['speedvideo', 'videomega', 'videott', 'vidhappy', 'vidto', 'vidzi'])

ALL_SERVERS = list(set(FREE_SERVERS))
ALL_SERVERS.sort()


def list_videos(pusher, item, data=None):
    logger.debug("start...")

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

    if data is None:
        item_url = item.item_info["extra.url"]
        data = scrapertools.cache_page(item_url)

    video_list = find_videos(data)

    for video in video_list:
        title = c.normalize("%s" % video[1])
        si = items.ServerItem(pusher, item, show_id, season, episode, video[0], title, "show_urls",
                              {"url": video[2]})

        si.properties["server"] = video[1]
        si.properties["video_id"] = video[3]
        item_list.append(si)

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


def find_videos(data):
    logger.debug("start...")

    video_list = []

    for server_id in ALL_SERVERS:
        try:
            server_package = "servers"
            server_module = __import__("%s.%s" % (server_package, server_id), fromlist=["%s" % server_package])
            if hasattr(server_module, "find_videos"):
                video_list.extend(server_module.find_videos(data))
        except ImportError:
            logger.error("The connector for [%s] doesn't exist." % server_id)
        except:
            logger.error("Error finding videos in [%s]" % server_id)

            import traceback, sys
            from pprint import pprint

            exc_type, exc_value, exc_tb = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_tb)
            for line in lines:
                line_splits = line.split("\n")
                for line_split in line_splits:
                    logger.error(line_split)

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


def get_video_url(pusher, item):
    logger.debug("start...")

    show_id = int(item.item_info["show_id"])
    season = int(item.item_info["item_season"])
    episode = int(item.item_info["item_episode"])
    server_id = item.item_info["item_server_id"]
    item_url = item.item_info["extra.url"]

    mi = None

    video_urls, succeeded, reason = resolve_video_urls_for_playing(server_id, item_url)
    if not succeeded:
        gui.error_dialog(reason)
        choice = -1
    else:
        if len(video_urls) == 1:
            choice = 0
        else:
            options = []
            for title, url in video_urls:
                options.append(title)
            choice = gui.show_select_dialog(config.get_localized_string(30957), options)

    if choice >= 0:
        title = video_urls[choice][0]
        url = video_urls[choice][1]
        mi = items.MediaItem(pusher, item, show_id, season, episode, server_id, url, title, "play_media")
        mi.properties["quality"] = video_urls[choice][0]
        mi.properties["path"] = video_urls[choice][1]
    logger.debug("end...")

    return mi


def resolve_video_urls_for_playing(server_id, url):
    logger.debug("start...")
    video_urls = []
    progress = None
    try:
        progress = gui.progress_dialog(None, config.get_localized_string(30950), 0)
        try:
            server_package = "servers"
            server_module = __import__("%s.%s" % (server_package, server_id), fromlist=["%s" % server_package])
            if hasattr(server_module, "get_video_url"):
                gui.progress_dialog(progress, config.get_localized_string(30951), 33)
                '''
                if not scrapertools.checkUrl(url):
                    logger.info(url)
                    gui.progress_dialog(progress, config.get_localized_string(30956), 100)
                    logger.debug("end...")
                    return video_urls, False, config.get_localized_string(30953)
                '''
                gui.progress_dialog(progress, config.get_localized_string(30952), 66)
                video_urls = server_module.get_video_url(url)

                if len(video_urls) == 0:
                    gui.progress_dialog(progress, config.get_localized_string(30956), 100)
                    logger.debug("end...")
                    return video_urls, False, config.get_localized_string(30954)

                gui.progress_dialog(progress, config.get_localized_string(30956), 100)
            else:
                gui.progress_dialog(progress, config.get_localized_string(30956), 100)
                logger.debug("end...")
                return video_urls, False, config.get_localized_string(30955)

        except ImportError:
            logger.error("The connector for [%s] doesn't exist." % server_id)
            gui.progress_dialog(progress, config.get_localized_string(30956), 100)
            logger.debug("end...")
            return video_urls, False, config.get_localized_string(30955)

    except:
        gui.progress_dialog(progress, config.get_localized_string(30956), 100)
        import traceback
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        logger.debug("end...")
        return video_urls, False, config.get_localized_string(30955)

    logger.debug("end...")
    return video_urls,True,""