import xbmcgui
import xbmcaddon
import xbmc
import time
import os
import sys
import urllib
import xbmcplugin
import xbmcgui
import xbmcaddon
import xbmc
import os
import json
import re
pyv3 = False
if sys.version_info[0] == 2:
    import urllib2
    from urllib import urlopen
    from urllib2 import urlopen as urlopen2
    from urllib import quote, quote_plus, unquote, unquote_plus
    import cookielib
else:
    import xbmcvfs
    import urllib.request
    from urllib.request import urlopen
    from urllib.request import urlopen as urlopen2
    from urllib.parse import quote, quote_plus, unquote, unquote_plus
    import http.cookiejar as cookielib
    pyv3 = True

class NoRedirectHandler(urllib.request.HTTPRedirectHandler if sys.version_info[0] >= 3 else urllib2.HTTPRedirectHandler):
    def http_error_302(self, req, fp, code, msg, headers):
        return headers
    http_error_301 = http_error_302
    http_error_303 = http_error_302
    http_error_307 = http_error_302

def PlayUrl(name, url, iconimage=None):
    # Standard User-Agent for consistency
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'

    # ZERO-TOUCH STRATEGY FOR LIVE STREAMS
    # Connecting to the redirector (load balancer) in Python counts as a "connection" on the server side.
    # This prevents Kodi from playing (Error 555 - Max Connections).
    # so we MUST NOT touch the network in Python for Live streams.
    # We pass the original URL to Kodi with the User-Agent, letting Kodi handle the full chain.
    if '/live/' in url or url.endswith('.ts'):
        xbmc.log('--- Live Stream detected: Bypassing Python resolution to avoid Session Lock.', 2)
        if '|' not in url:
            url += '|User-Agent=' + quote(user_agent)
        xbmc.log('--- Playing (Zero-Touch) "{0}". {1}'.format(name, url), 2)
        listitem = xbmcgui.ListItem(path=url)
        listitem.setArt({'icon': iconimage, 'thumb': iconimage})
        listitem.setInfo(type="Video", infoLabels={"mediatype": "movie", "Title": name})
        
        # DISABLING PROBING:
        # Prevent Kodi from opening a preliminary connection to check headers/codecs.
        # This ensures strictly ONE connection is made (for playback), preventing 555 errors.
        listitem.setContentLookup(False)
        listitem.setMimeType('video/mp2t')
        
        if iconimage is not None:
            try:
                listitem.setArt({'thumb': iconimage})
            except:
                listitem.setThumbnailImage(iconimage)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
        return

    try:
        # Resolve redirects RECURSIVELY with COOKIES and UA (For Movies/VOD)
        
        cj = cookielib.CookieJar()
        max_redirects = 5
        current_redirects = 0
        resolved_url = url
        
        while current_redirects < max_redirects:
            try:
                if pyv3:
                    opener = urllib.request.build_opener(NoRedirectHandler, urllib.request.HTTPCookieProcessor(cj))
                    opener.addheaders = [('User-Agent', user_agent)]
                else:
                    opener = urllib2.build_opener(NoRedirectHandler, urllib2.HTTPCookieProcessor(cj))
                    opener.addheaders = [('User-Agent', user_agent)]
                
                response = opener.open(resolved_url)
                
                new_url = None
                # Check for redirect in headers
                # Case 1: Intercepted 302 (response is headers object, has .get)
                # Check for redirect in headers (since we intercepted it)
                if hasattr(response, 'get'):
                    new_url = response.get('Location') or response.get('location')
                    if new_url:
                        if new_url == resolved_url:
                            break
                        resolved_url = new_url
                        current_redirects += 1
                        xbmc.log('--- Redirect {0}: {1}'.format(current_redirects, resolved_url), 2)
                    else:
                        break # No redirect headerfound (200 OK or end of chain) -> Stop loop!
                # Close the connection if it's a real response object to free the slot
                if hasattr(response, 'close'):
                    response.close()
                break 
            except Exception as e:
                # If 555 or other error, break and try current resolved_url
                xbmc.log('--- HTTP Error / End of chain: {0}'.format(str(e)), 2)
                break

        # Format cookies for Kodi
        cookie_string = ""
        try:
            cookie_string = "; ".join(["{}={}".format(cookie.name, cookie.value) for cookie in cj])
        except: pass

        # Append headers to final URL for Kodi
        if resolved_url:
            url = resolved_url
            if '|' not in url:
                url += '|User-Agent=' + quote(user_agent)
                if cookie_string:
                    url += '&Cookie=' + quote(cookie_string)
            xbmc.log('--- Final Resolved URL: {0}'.format(url), 2)
            
    except Exception as general_e:
        xbmc.log('--- Error Resolving URL: {0} - {1}'.format(url, str(general_e)), 2)
        pass

    xbmc.log('--- Playing "{0}". {1}'.format(name, url), 2)
    listitem = xbmcgui.ListItem(path=url)
    listitem.setArt({'icon': iconimage, 'thumb': iconimage})
    listitem.setInfo(type="Video", infoLabels={
                     "mediatype": "movie", "Title": name})
    if iconimage is not None:
        try:
            listitem.setArt({'thumb': iconimage})
        except:
            listitem.setThumbnailImage(iconimage)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)

# --- FIX CODIFICA CARATTERI ---
# --- FIX CODIFICA CARATTERI ---
def FixString(text):
    if not text: return ""
    
    # Unify text to unicode (Py2) or str (Py3) for processing
    current = text
    if not pyv3: # Python 2
        if isinstance(current, str):
            try: current = current.decode('utf-8')
            except: 
                try: current = current.decode('latin-1')
                except: pass
    
    # Loop per gestire mojibake multipli (es. utf8 -> cp1252 -> utf8 -> cp1252)
    for _ in range(3): # Prova fino a 3 livelli
        try:
            # Usa CP1252 invece di latin-1 per coprire char come 'ƒ' (0x83)
            # In Py3: str -> bytes(cp1252) -> str(utf8)
            # In Py2: unicode -> str(cp1252) -> unicode(utf8)
            decoded = current.encode('cp1252').decode('utf-8')
            if decoded == current: break
            current = decoded
        except:
            try:
                # Fallback a latin-1
                decoded = current.encode('latin-1').decode('utf-8')
                if decoded == current: break
                current = decoded
            except:
                break # Stop se non decodificabile

    # Return correct type
    if not pyv3: # Python 2: return utf-8 encoded str
        if isinstance(current, unicode):
            return current.encode('utf-8')
    return current

def unquote_c(value):
    if not value: return ""
    try:
        if pyv3:
            return FixString(unquote(value))
        else:
            return FixString(unquote(value.encode('latin1')).decode('utf-8'))
    except:
        return value

def unquote_plus_c(value):
    if pyv3:
        return unquote_plus(value)
    else:
        return unquote_plus(value.encode('latin1'))

def traslatePath(path):
    if pyv3:
        return xbmcvfs.translatePath(path)
    else:
        return xbmc.translatePath(path)

AddonID = 'plugin.video.iptvaddons'
Addon = xbmcaddon.Addon(AddonID)
AddonName = Addon.getAddonInfo("name")
icon = Addon.getAddonInfo('icon')

addonDir = Addon.getAddonInfo('path')

libDir = os.path.join(addonDir, 'resources', 'lib')
sys.path.insert(0, libDir)
if pyv3:
    import common3 as common
else:
    import common

addon_data_dir = os.path.join(traslatePath(
    "special://userdata/addon_data"), AddonID)
addon_extra_data_dir = os.path.join(traslatePath(
    "special://userdata/addon_data"), 'pvr.iptvsimple')
addon_oscam_config_dir = os.path.join(traslatePath(
    "special://userdata/addon_data"), 'service.softcam.oscam', 'config')
if not os.path.exists(addon_data_dir):
    os.makedirs(addon_data_dir)

playlistsFile = os.path.join(addon_data_dir, "playLists.txt")
codelistsFile = os.path.join(addon_extra_data_dir, "settings.xml")
oscamlistFile = os.path.join(addon_oscam_config_dir, 'oscam.server')
tmpListFile = os.path.join(addon_data_dir, 'tempList.txt')
favoritesFile = os.path.join(addon_data_dir, 'favorites.txt')
code = 'none'
#sitom = 'https://md1.qp1.in/u/'
#sitoi = "https://md1.ipset.in/img/"
sitom = Addon.getSetting('base_url')
if not sitom: sitom = 'https://md1.qp1.in/u/'
if not sitom.endswith('/'): sitom += '/'

sitoi = Addon.getSetting('image_url')
if not sitoi: sitoi = 'https://md1.ipset.in/img/'
if not sitoi.endswith('/'): sitoi += '/'
if not (os.path.isfile(favoritesFile)):
    f = open(favoritesFile, 'w')
    f.write('[]')
    f.close()


def read_from_file(path, silent=False):
    try:
        f = open(path, 'r')
        r = f.read()
        f.close()
        return str(r)
    except:
        if not silent:
            print("Could not read from " + path)
        return None


def getLocaleString(id):
    return Addon.getLocalizedString(id).encode('utf-8')


def Categories():
    kcode = GetKeyboardText("Inserisci password", "")
    if kcode == "999111":
        try:
            xbmcplugin.setContent(int(sys.argv[1]), 'movies')
            xbmc.executebuiltin('Container.SetViewMode(500)')
            
            icon = sitoi + 'xxxvetrina.jpg'
            back = sitoi + 'xxxcover.jpg'
            for line in urlopen(sitom + code + "/jgruppilivexxx/listin.txt"):
                line = line.decode('utf-8')
                urln, nomem = line.split(';')
                nomem = u'[COLOR red]LIVE:[/COLOR] [COLOR white]' + FixString(nomem.strip()) + '[/COLOR]'
                AddDir(nomem, sitom +
                       code + "/jgruppilivexxx/" + urln, 1, icon, background=back)
            for line in urlopen(sitom + code + "/jgruppixxx/listin.txt"):
                line = line.decode('utf-8')
                urln, nomem, icon, back = line.split(';')
                nomem = u'[COLOR gold]VOD:[/COLOR] [COLOR white]' + FixString(nomem.strip()) + '[/COLOR]'
                AddDir(nomem, sitom +
                       code + "/jgruppixxx/" + urln, 1, icon, background=back.strip())
            for line in urlopen(sitom + code + "/jlistexxx/listin.txt"):
                line = line.decode('utf-8')
                urln, nomem, icon, back = line.split(';')
                AddDir("[COLOR lightblue]" + FixString(nomem.strip()) + "[/COLOR]", sitom +
                       code + "/jlistexxx/" + urln, 1, icon, background=back.strip())
        except Exception as e:
            xbmc.executebuiltin('Notification(IPTVAdulti, Errore Caricamento Categorie: ' + str(e) + ', 3000, ' + icon + ')')


def AddNewList():
    listName = GetKeyboardText(getLocaleString(10004)).strip()
    if len(listName) < 1:
        return
    listUrl = GetChoice(10002, 10005, 10006, 10016, 10017,
                        fileType=1, fileMask='.json|.m3u|.m3u8')
    if len(listUrl) < 1:
        return
    image = GetChoice(10022, 10022, 10022, 10024, 10025, 10021, fileType=2)
    if listUrl.endswith('.json'):
        logosUrl = ''
    else:
        logosUrl = GetChoice(10018, 10019, 10020, 10019,
                             10020, 10021, fileType=0)
        if logosUrl.startswith('http') and not logosUrl.endswith('/'):
            logosUrl += '/'
    list = common.ReadList(playlistsFile)
    for item in list:
        if item["url"].lower() == listUrl.lower():
            xbmc.executebuiltin('Notification({0}, "{1}" {2}, 5000, {3})'.format(
                AddonName, listName, getLocaleString(10007), icon))
            return
    list.append({"name": listName, "url": listUrl,
                 "image": image, "logos": logosUrl})
    if common.SaveList(playlistsFile, list):
        xbmc.executebuiltin("XBMC.Container.Refresh()")


def GetChoice(choiceTitle, fileTitle, urlTitle, choiceFile, choiceUrl, choiceNone=None, fileType=1, fileMask=None, defaultText=""):
    choice = ''
    choiceList = [getLocaleString(choiceFile), getLocaleString(choiceUrl)]
    if choiceNone != None:
        choiceList.append(getLocaleString(choiceNone))
    method = GetSourceLocation(getLocaleString(choiceTitle), choiceList)
    if method == 0:
        if not defaultText.startswith('http'):
            defaultText = ""
        choice = GetKeyboardText(getLocaleString(
            fileTitle), defaultText).strip()
    elif method == 1:
        if defaultText.startswith('http'):
            defaultText = ""
        choice = xbmcgui.Dialog().browse(fileType, getLocaleString(urlTitle),
                                         'myprograms', fileMask, False, False, defaultText)
    return choice


def RemoveFromLists(index, listFile):
    list = common.ReadList(listFile)
    if index < 0 or index >= len(list):
        return
    del list[index]
    common.SaveList(listFile, list)
    xbmc.executebuiltin("XBMC.Container.Refresh()")


def JsonCategory(url):
    tmpList = []
    name = u'nessun nome'
    
    # Enable Thumbnail/Wall View
    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmc.executebuiltin('Container.SetViewMode(500)')
    try:
        response = urlopen(url)
        content = response.read()
        if pyv3: content = content.decode('utf-8')
        list = json.loads(content)
        
        for channel in list:
            iconimage = unquote(channel["stream_icon"])
            name = unquote_c(channel["name"])
            url = unquote(channel["url"])
            bkg = unquote(channel["background"])
            AddDir(name, url, 3, iconimage, isFolder=False, background=bkg,
                   descrizione=unquote_c(channel["descrizione"]))
            tmpList.append({"url": url, "image": iconimage, "name": name})
    except Exception as e:
        xbmc.executebuiltin('Notification(IPTVAdulti, Errore Caricamento Canali, 3000, ' + icon + ')')

    common.SaveList(tmpListFile, tmpList)


def m3uCategory(url, logos):
    # Enable Thumbnail/Wall View
    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmc.executebuiltin('Container.SetViewMode(500)')
    
    tmpList = []
    list = common.m3u2list(url)

    for channel in list:
        name = channel.get("display_name", "Sconosciuto")
        image = channel.get("tvg_logo", "")
        if image == "":
            image = channel.get("logo", "")
        if logos is not None and logos != '' and image is not None and image != '' and not image.startswith('http'):
            image = logos + image
        url = common.GetEncodeString(channel["url"])
        AddDir(name, url, 3, image, isFolder=False)
        tmpList.append({"url": url, "image": image, "name": name})

    common.SaveList(tmpListFile, tmpList)





def AddDir(name, url, mode, iconimage, logos="", index=-1, move=0, isFolder=True, background=None, descrizione=None):
    u = sys.argv[0]+"?url="+quote_plus(url)+"&mode="+str(mode)+"&name="+quote_plus(name)+"&iconimage="+quote_plus(
        iconimage)+"&logos="+quote_plus(logos)+"&index="+str(index)+"&move="+str(move)
    liz = xbmcgui.ListItem(name)
    liz.setArt({'icon': iconimage, 'thumb': iconimage})
    if descrizione == None:
        descrizione = name
    
    info_labels = {'title': name, 'plot': descrizione}
    if '/live/' in url or url.endswith('.ts'):
        info_labels['mediatype'] = 'video'
    elif mode == 3:
        info_labels['mediatype'] = 'movie'
        
    liz.setInfo(type="Video", infoLabels=info_labels)
    listMode = 21  # Lists
    if background != None:
        liz.setProperty('fanart_image', background)
    if mode == 1 or mode == 2:
        items = [(getLocaleString(10008), 'XBMC.RunPlugin({0}?index={1}&mode=22)'.format(sys.argv[0], index)),
                 (getLocaleString(10026), 'XBMC.RunPlugin({0}?index={1}&mode=23)'.format(
                     sys.argv[0], index)),
                 (getLocaleString(10027), 'XBMC.RunPlugin({0}?index={1}&mode=24)'.format(
                     sys.argv[0], index)),
                 (getLocaleString(10028), 'XBMC.RunPlugin({0}?index={1}&mode=25)'.format(sys.argv[0], index))]
        if mode == 2:
            items.append((getLocaleString(
                10029), 'XBMC.RunPlugin({0}?index={1}&mode=26)'.format(sys.argv[0], index)))
    elif mode == 3:
        liz.setProperty('IsPlayable', 'true')
        liz.addContextMenuItems(items=[('{0}'.format(getLocaleString(
            10009)), 'XBMC.RunPlugin({0}?url={1}&mode=31&iconimage={2}&name={3})'.format(sys.argv[0], quote_plus(url), iconimage, name))])
    elif mode == 32:
        liz.setProperty('IsPlayable', 'true')
        items = [(getLocaleString(10010), 'XBMC.RunPlugin({0}?index={1}&mode=33)'.format(sys.argv[0], index)),
                 (getLocaleString(10026), 'XBMC.RunPlugin({0}?index={1}&mode=35)'.format(
                     sys.argv[0], index)),
                 (getLocaleString(10027), 'XBMC.RunPlugin({0}?index={1}&mode=36)'.format(
                     sys.argv[0], index)),
                 (getLocaleString(10028), 'XBMC.RunPlugin({0}?index={1}&mode=37)'.format(sys.argv[0], index))]
        listMode = 38  # Favourits
    if mode == 1 or mode == 2 or mode == 32:
        items += [(getLocaleString(10030), 'XBMC.RunPlugin({0}?index={1}&mode={2}&move=-1)'.format(sys.argv[0], index, listMode)),
                  (getLocaleString(10031), 'XBMC.RunPlugin({0}?index={1}&mode={2}&move=1)'.format(
                      sys.argv[0], index, listMode)),
                  (getLocaleString(10032), 'XBMC.RunPlugin({0}?index={1}&mode={2}&move=0)'.format(sys.argv[0], index, listMode))]
        liz.addContextMenuItems(items)

    xbmcplugin.addDirectoryItem(handle=int(
        sys.argv[1]), url=u, listitem=liz, isFolder=isFolder)


def GetKeyboardText(title="", defaultText=""):
    keyboard = xbmc.Keyboard(defaultText, title)
    keyboard.doModal()
    text = "" if not keyboard.isConfirmed() else keyboard.getText()
    return text


def GetSourceLocation(title, list):
    dialog = xbmcgui.Dialog()
    answer = dialog.select(title, list)
    return answer


def AddFavorites(url, iconimage, name):
    favList = common.ReadList(favoritesFile)
    for item in favList:
        if item["url"].lower() == url.lower():
            xbmc.executebuiltin("Notification({0}, '{1}' {2}, 5000, {3})".format(
                AddonName, name, getLocaleString(10011), icon))
            return
    list = common.ReadList(tmpListFile)
    for channel in list:
        if channel["name"].lower() == name.lower():
            url = channel["url"].encode("utf-8")
            iconimage = channel["image"].encode("utf-8")
            break
    if not iconimage:
        iconimage = ""
    data = {"url": url, "image": iconimage, "name": name}
    favList.append(data)
    common.SaveList(favoritesFile, favList)
    xbmc.executebuiltin("Notification({0}, '{1}' {2}, 5000, {3})".format(
        AddonName, name, getLocaleString(10012), icon))


def ListFavorites():
    AddDir("[COLOR yellow][B]{0}[/B][/COLOR]".format(getLocaleString(10013)), "favorites", 34,
           os.path.join(addonDir, "resources", "images", "bright_yellow_star.png"), isFolder=False)
    list = common.ReadList(favoritesFile)
    i = 0
    for channel in list:
        AddDir(channel["name"].encode("utf-8"), channel["url"].encode("utf-8"),
               32, channel["image"].encode("utf-8"), index=i, isFolder=False)
        i += 1


def AddNewFavorite():
    chName = GetKeyboardText(getLocaleString(10014))
    if len(chName) < 1:
        return
    chUrl = GetKeyboardText(getLocaleString(10015))
    if len(chUrl) < 1:
        return
    image = GetChoice(10023, 10023, 10023, 10024, 10025, 10021, fileType=2)

    favList = common.ReadList(favoritesFile)
    for item in favList:
        if item["url"].lower() == chUrl.lower():
            xbmc.executebuiltin("Notification({0}, '{1}' {2}, 5000, {3})".format(
                AddonName, chName, getLocaleString(10011), icon))
            return

    data = {"url": chUrl, "image": image, "name": chName}

    favList.append(data)
    if common.SaveList(favoritesFile, favList):
        xbmc.executebuiltin("XBMC.Container.Refresh()")


def ChangeKey(index, listFile, key, title):
    list = common.ReadList(listFile)
    str = GetKeyboardText(getLocaleString(
        title), list[index][key].encode("utf-8"))
    if len(str) < 1:
        return
    list[index][key] = str
    if common.SaveList(listFile, list):
        xbmc.executebuiltin("XBMC.Container.Refresh()")


def ChangeChoice(index, listFile, key, choiceTitle, fileTitle, urlTitle, choiceFile, choiceUrl, choiceNone=None, fileType=1, fileMask=None):
    list = common.ReadList(listFile)
    if key == "logos":
        listUrl = list[index].get("url", "")
        if listUrl.endswith('.json'):
            return
    defaultText = list[index].get(key, "")
    str = GetChoice(choiceTitle, fileTitle, urlTitle, choiceFile, choiceUrl,
                    choiceNone, fileType, fileMask, defaultText.encode("utf-8"))
    if key == "url" and len(str) < 1:
        return
    elif key == "logos" and str.startswith('http') and not str.endswith('/'):
        str += '/'
    list[index][key] = str
    if common.SaveList(listFile, list):
        xbmc.executebuiltin("XBMC.Container.Refresh()")


def MoveInList(index, step, listFile):
    theList = common.ReadList(listFile)
    if index + step >= len(theList) or index + step < 0:
        return
    if step == 0:
        step = GetIndexFromUser(len(theList), index)
    if step < 0:
        tempList = theList[0:index + step] + [theList[index]] + \
            theList[index + step:index] + theList[index + 1:]
    elif step > 0:
        tempList = theList[0:index] + theList[index + 1:index +
                                              1 + step] + [theList[index]] + theList[index + 1 + step:]
    else:
        return
    common.SaveList(listFile, tempList)
    xbmc.executebuiltin("XBMC.Container.Refresh()")


def GetIndexFromUser(listLen, index):
    dialog = xbmcgui.Dialog()
    location = dialog.input(
        '{0} (1-{1})'.format(getLocaleString(10033), listLen), type=xbmcgui.INPUT_NUMERIC)
    if location is None or location == "":
        return 0
    try:
        location = int(location) - 1
        if location >= listLen or location < 0:
            return 0
    except:
        return 0
    return location - index


def get_params():
    param = []
    paramstring = sys.argv[2]
    if len(paramstring) >= 2:
        params = sys.argv[2]
        cleanedparams = params.replace('?', '')
        if (params[len(params)-1] == '/'):
            params = params[0:len(params)-2]
        pairsofparams = cleanedparams.split('&')
        param = {}
        for i in range(len(pairsofparams)):
            splitparams = {}
            splitparams = pairsofparams[i].split('=')
            if (len(splitparams)) == 2:
                param[splitparams[0].lower()] = splitparams[1]
    return param


if os.path.exists(addon_oscam_config_dir):
    u = 'none'
    p = 'none'
    allsettings = read_from_file(oscamlistFile)
    match = re.compile('(.*)').findall(allsettings)
    for line in match:
        if line[0:1] != "#":
            if line.find("user") >= 0:
                line = re.sub(" ", "", line)
                line = re.sub("\n", "", line)
                e, u = line.decode().split('=')
            if line.find("password") >= 0:
                line = re.sub(" ", "", line)
                line = re.sub("\n", "", line)
                e, p = line.decode().split('=')
    code = u + p
elif os.path.exists(addon_extra_data_dir):
    allsettings = read_from_file(codelistsFile)
    match = re.compile('setting id="(.+?)" value="(.+?)"').findall(allsettings)
    for id, value in match:
        if id == "m3uUrl":
            if value != '':
                h, n, v, u, o, i = value.split('/')
                code = o

if code == "none" and os.path.exists(addon_extra_data_dir):
    allsettings = read_from_file(codelistsFile)
    match = re.compile('>(.+?)<').findall(allsettings)
    for value in match:
        if value[-3:] == 'm3u':
            h, n, v, u, o, i = value.split('/')
            code = o

params = get_params()
url = None
logos = None
name = None
mode = None
iconimage = None
description = None

try:
    url = unquote_plus(params["url"])
except:
    pass
try:
    logos = unquote_plus(params.get("logos", ''))
except:
    pass
try:
    name = unquote_plus(params["name"])
except:
    pass
try:
    iconimage = unquote_plus(params["iconimage"])
except:
    pass
try:
    mode = int(params["mode"])
except:
    pass
try:
    index = int(params["index"])
except:
    pass
try:
    move = int(params["move"])
except:
    pass


if mode == None:
    Categories()
elif mode == 1:
    JsonCategory(url)
elif mode == 2:
    m3uCategory(url, logos)
elif mode == 3 or mode == 32:
    PlayUrl(name, url, iconimage)
elif mode == 20:
    AddNewList()
elif mode == 21:
    MoveInList(index, move, playlistsFile)
elif mode == 22:
    RemoveFromLists(index, playlistsFile)
elif mode == 23:
    ChangeKey(index, playlistsFile, "name", 10004)
elif mode == 24:
    ChangeChoice(index, playlistsFile, "url", 10002, 10005,
                 10006, 10016, 10017, None, 1, '.json|.m3u|.m3u8')
elif mode == 25:
    ChangeChoice(index, playlistsFile, "image", 10022,
                 10022, 10022, 10024, 10025, 10021, 2)
elif mode == 26:
    ChangeChoice(index, playlistsFile, "logos", 10018,
                 10019, 10020, 10019, 10020, 10021, 0)
elif mode == 27:
    common.DelFile(playlistsFile)
    sys.exit()
elif mode == 30:
    ListFavorites()
elif mode == 31:
    AddFavorites(url, iconimage, name)
elif mode == 33:
    RemoveFromLists(index, favoritesFile)
elif mode == 34:
    AddNewFavorite()
elif mode == 35:
    ChangeKey(index, favoritesFile, "name", 10014)
elif mode == 36:
    ChangeKey(index, favoritesFile, "url", 10015)
elif mode == 37:
    ChangeChoice(index, favoritesFile, "image", 10023,
                 10023, 10023, 10024, 10025, 10021, 2)
elif mode == 38:
    MoveInList(index, move, favoritesFile)
elif mode == 39:
    common.DelFile(favoritesFile)
    sys.exit()
elif mode == 40:
    import glob
    cache_files = glob.glob(os.path.join(addon_data_dir, "*.json"))
    for f in cache_files:
        try: os.remove(f)
        except: pass
    xbmc.executebuiltin('Notification({0}, {1}, 3000, {2})'.format(AddonName, "Cache Svuotata / Cache Cleared", icon))
    sys.exit()
elif mode == 41:
    # Test Encoding Fix
    broken = "lÃ¢â‚¬â„¢affair"
    fixed = FixString(broken)
    xbmcgui.Dialog().ok("Test Encoding", "Original: " + broken + "\nFixed: " + fixed)
    sys.exit()

xbmcplugin.endOfDirectory(int(sys.argv[1]))
