# -*- coding: utf-8 -*-

from resources.lib.home import cHome
from resources.lib.gui.gui import cGui
from resources.lib.handler.pluginHandler import cPluginHandler
from resources.lib.handler.inputParameterHandler import cInputParameterHandler
from resources.lib.handler.outputParameterHandler import cOutputParameterHandler
from resources.lib.comaddon import progress, VSlog, addon, window, siteManager, addonManager
from resources.lib.search import cSearch
import re

DEBUG = False

# A legitimate dispatch target is always a bare Python identifier (e.g. 'load',
# 'showMovies'). The plugin URL is attacker-controllable (sys.argv[2]), so the
# 'site'/'function' parameters must never be string-interpolated into exec().
_VALID_NAME = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')


def _safe_call(obj, sFunction):
    """Call obj.<sFunction>() by name without exec(). Blocks code injection via
    the plugin URL while preserving all legitimate navigation (function names
    are plain identifiers)."""
    if not isinstance(sFunction, str) or not _VALID_NAME.match(sFunction):
        VSlog('WikiFleaks: blocked invalid function name: %s' % repr(sFunction))
        return
    method = getattr(obj, sFunction, None)
    if callable(method):
        method()
    else:
        VSlog('WikiFleaks: blocked unknown/non-callable function: %s' % sFunction)

if DEBUG:

    import sys
    sys.path.append('H:\Program Files\Kodi\system\Python\Lib\pysrc')

    try:
        import pysrc.pydevd as pydevd
        pydevd.settrace('localhost', stdoutToServer=True, stderrToServer=True)
    except ImportError:
        try:
            import pydevd
            pydevd.settrace('localhost', stdoutToServer=True, stderrToServer=True)
        except ImportError:
            sys.stderr.write("Error: " + "You must add org.python.pydev.debug.pysrc to your PYTHONPATH.")


class main:

    def __init__(self):
        self.parseUrl()

    def parseUrl(self):
        oPluginHandler = cPluginHandler()
        pluginPath = oPluginHandler.getPluginPath()
        if pluginPath == 'plugin://plugin.video.wikifleaks/extrafanart/':
            return

        oInputParameterHandler = cInputParameterHandler()

        if oInputParameterHandler.exist('function'):
            sFunction = oInputParameterHandler.getValue('function')
        else:
            VSlog('call load methode')
            sFunction = "load"

        if sFunction == 'setSetting':
            addon_id = None
            if oInputParameterHandler.exist('addon'):
                addon_id = oInputParameterHandler.getValue('addon')

            if oInputParameterHandler.exist('id'):
                plugin_id = oInputParameterHandler.getValue('id')
            else:
                return

            if oInputParameterHandler.exist('value'):
                value = oInputParameterHandler.getValue('value')
            else:
                return

            setSetting(addon_id, plugin_id, value)
            return

        if sFunction == 'setSettings':
            setSettings(oInputParameterHandler)
            return

        if sFunction == 'DoNothing':
            return

        if not oInputParameterHandler.exist('site'):
            plugins = __import__('resources.lib.home', fromlist=['home']).cHome()
            function = getattr(plugins, 'load')
            function()
            return

        if oInputParameterHandler.exist('site'):
            sSiteName = oInputParameterHandler.getValue('site')
            VSlog('load site ' + sSiteName + ' and call function ' + sFunction)

            if isHosterGui(sSiteName, sFunction):
                return

            if isGui(sSiteName, sFunction):
                return

            if isFav(sSiteName, sFunction):
                return

            if isRecommendations(sSiteName, sFunction):
                return

            if isWatched(sSiteName, sFunction):
                return

            if isViewing(sSiteName, sFunction):
                return

            if isLibrary(sSiteName, sFunction):
                return

            if isDl(sSiteName, sFunction):
                return

            if isHome(sSiteName, sFunction):
                return

            if isTrakt(sSiteName, sFunction):
                return

            if isSearch(sSiteName, sFunction):
                return

            if sSiteName == 'globalRun':
                __import__('resources.lib.runscript', fromlist=['runscript'])
                return

            if sSiteName in ('globalSources', 'sportSources', 'animeSources'):
                oGui = cGui()
                aPlugins = oPluginHandler.getAvailablePlugins(force=(sFunction in ('globalSources', 'sportSources', 'animeSources')))

                sitesManager = siteManager()
                isSportSources = (sSiteName == 'sportSources')
                isAnimeSources = (sSiteName == 'animeSources')

                if len(aPlugins) == 0:
                    addons = addon()
                    addons.openSettings()
                    oGui.updateDirectory()
                else:
                    for aPlugin in aPlugins:
                        isSport = sitesManager.isSport(aPlugin[1])
                        isAnime = sitesManager.isAnime(aPlugin[1])
                        isTorrent = sitesManager.isTorrent(aPlugin[1])
                        if isSportSources and not isSport:
                            continue
                        if isAnimeSources and not isAnime:
                            continue
                        if not isSportSources and not isAnimeSources and (isSport or isAnime or isTorrent):
                            continue

                        sitename = aPlugin[0]
                        if not sitesManager.isActive(aPlugin[1]):
                            sitename = '[COLOR red][OFF] ' + sitename + '[/COLOR]'

                        oOutputParameterHandler = cOutputParameterHandler()
                        oOutputParameterHandler.addParameter('siteUrl', 'http://venom')
                        icon = 'sites/%s.png' % (aPlugin[1])
                        oGui.addDir(aPlugin[1], 'load', sitename, icon, oOutputParameterHandler)

                oGui.setEndOfDirectory()
                return

            if sSiteName == 'globalParametre':
                addons = addon()
                addons.openSettings()
                return

            if not (_VALID_NAME.match(sSiteName or '') and _VALID_NAME.match(sFunction or '')):
                VSlog('WikiFleaks: blocked invalid site/function: %s / %s' % (repr(sSiteName), repr(sFunction)))
                return

            try:
                plugins = __import__('resources.sites.%s' % sSiteName, fromlist=[sSiteName])
                function = getattr(plugins, sFunction)
                function()
            except Exception as e:
                progress().VSclose()
                VSlog('could not load site: ' + sSiteName + ' error: ' + str(e))
                import traceback
                traceback.print_exc()
                return


def setSetting(addon_id, param, value):
    
    if addon_id:
        if 'wikifleaks_source_' in addon_id:
            return siteManager().setProperty(addon_id.replace('wikifleaks_source_', ''), param, value)
        return addonManager().setSettingAddon(addon_id, param, value)
    
    addons = addon()
    setting = addons.getSetting(param)

    if setting != value:
        addons.setSetting(param, value)
        return True

    return False

def setSettings(oInputParameterHandler):
    addons = addon()

    for i in range(1, 100):
        plugin_id = oInputParameterHandler.getValue('id' + str(i))
        if plugin_id:
            value = oInputParameterHandler.getValue('value' + str(i))
            value = value.replace('\n', '')
            oldSetting = addons.getSetting(plugin_id)
            if oldSetting != value:
                addons.setSetting(plugin_id, value)

    return True


def isHosterGui(sSiteName, sFunction):
    if sSiteName == 'cHosterGui':
        plugins = __import__('resources.lib.gui.hoster', fromlist=['cHosterGui']).cHosterGui()
        function = getattr(plugins, sFunction)
        function()
        return True
    return False


def isGui(sSiteName, sFunction):
    if sSiteName == 'cGui':
        oGui = cGui()
        _safe_call(oGui, sFunction)
        return True
    return False


def isFav(sSiteName, sFunction):
    if sSiteName == 'cFav':
        plugins = __import__('resources.lib.bookmark', fromlist=['cFav']).cFav()
        function = getattr(plugins, sFunction)
        function()
        return True
    return False

def isRecommendations(sSiteName, sFunction):
    if sSiteName == 'cRecommendations':
        plugins = __import__('resources.lib.recommendations', fromlist=['cRecommendations']).cRecommendations()
        function = getattr(plugins, sFunction)
        function()
        return True
    return False

def isWatched(sSiteName, sFunction):
    if sSiteName == 'cWatched':
        plugins = __import__('resources.lib.watched', fromlist=['cWatched']).cWatched()
        function = getattr(plugins, sFunction)
        function()
        return True
    return False


def isViewing(sSiteName, sFunction):
    if sSiteName == 'cViewing':
        plugins = __import__('resources.lib.viewing', fromlist=['cViewing']).cViewing()
        function = getattr(plugins, sFunction)
        function()
        return True
    return False


def isLibrary(sSiteName, sFunction):
    if sSiteName == 'cLibrary':
        plugins = __import__('resources.lib.library', fromlist=['cLibrary']).cLibrary()
        function = getattr(plugins, sFunction)
        function()
        return True
    return False


def isDl(sSiteName, sFunction):
    if sSiteName == 'cDownload':
        plugins = __import__('resources.lib.download', fromlist=['cDownload']).cDownload()
        function = getattr(plugins, sFunction)
        function()
        return True
    return False


def isHome(sSiteName, sFunction):
    if sSiteName == 'cHome':
        oHome = cHome()
        _safe_call(oHome, sFunction)
        return True
    return False


def isTrakt(sSiteName, sFunction):
    if sSiteName == 'cTrakt':
        plugins = __import__('resources.lib.trakt', fromlist=['cTrakt']).cTrakt()
        function = getattr(plugins, sFunction)
        function()
        return True
    return False


def isSearch(sSiteName, sFunction):
    if sSiteName == 'globalSearch':
        oSearch = cSearch()
        oSearch.searchGlobal()
        return True
    return False


def _pluginSearch(plugin, sSearchText):

    window(10101).setProperty('search', 'true')

    try:
        plugins = __import__('resources.sites.%s' % plugin['identifier'], fromlist=[plugin['identifier']])
        function = getattr(plugins, plugin['search'][1])
        sUrl = plugin['search'][0] + str(sSearchText)

        function(sUrl)

        VSlog('Load Search: ' + str(plugin['identifier']))
    except:
        VSlog(plugin['identifier'] + ': search failed')

    window(10101).setProperty('search', 'false')


main()