import re, os, sys, time, json
import xbmc, xbmcaddon, xbmcgui, xbmcplugin
import requests

from urllib.parse import quote_plus, parse_qs ##, unquote, quote, urlencode, parse_qsl

try:
    import StorageServer
except:
    import storageserverdummy as StorageServer
cache = StorageServer.StorageServer("Phantom")

from resources.lib import cda, db, views, tools, dialog, kodisettings #, advancedsettings
from resources.lib import PhantomCommon, common, metadata


cm                      = PhantomCommon.common()
cnt                     = common.count()
sysaddon                = sys.argv[0]
addon_handle            = int(sys.argv[1])
args                    = parse_qs(sys.argv[2][1:])
my_addon                = xbmcaddon.Addon()
my_addon_id             = my_addon.getAddonInfo('id')
my_addon_name           = my_addon.getAddonInfo('name')

up_info             = my_addon.getSetting('up_info')
cda_login           = my_addon.getSetting('cda_login')
cda_user            = my_addon.getSetting('cda_user')
cda_pass            = my_addon.getSetting('cda_pass')
phantom_user        = my_addon.getSetting('phantom_user')
phantom_pass        = my_addon.getSetting('phantom_pass')
set_list_colours    = my_addon.getSetting('set_list_colours')
show_adult          = my_addon.getSetting('show_adult')
show_premium        = my_addon.getSetting('show_premium')

SERVICE     = 'cda'
COOKIEPATH  = my_addon.getAddonInfo('path') + os.path.sep + "cookies"
COOKIEFILE  = COOKIEPATH + os.path.sep + SERVICE + ".cookie"

s = requests.Session()

loginData   = {'username': cda_user, 'password': cda_pass}
mainUrl     = 'https://www.cda.pl'


def log(msg): xbmc.log('===default=== ' +msg, level=xbmc.LOGINFO)

colours = ('', 'red', 'green', 'blue', 'yellow')


def ownFolders():
    for i in range(1, 6):
        Fx = "F" + str(i)
        if my_addon.getSetting(Fx) == "true":
            add(my_addon.getSetting(Fx + "_nazwa"), seturl(Fx), 'FilmList', True)

def categories():
    if my_addon.getSetting('save_viewed') != '0':
        add('Historia oglądania', '0', 'ViewedList', True)
    add('[COLOR=%s]Phantom Extra[/COLOR]' % ('blue' if set_list_colours == 'true' else ''), '0', 'PhantomExtra',True)
    add('[COLOR=%s]Filmy - HD[/COLOR]' % ('red' if set_list_colours == 'true' else ''), db.readParam(11) + 'duration=dlugie&section=&quality=720p&section=&s=date&section=', 'FilmList',True)
    add('[COLOR=%s]Filmy - najnowsze[/COLOR]' % ('green' if set_list_colours == 'true' else ''), db.readParam(11) + 'duration=dlugie&s=date', 'FilmList',True)
    add('Filmy - PREMIUM', mainUrl + '/premium', 'PremiumCategory',True)
    add('[COLOR=%s]Video - najnowsze[/COLOR]' % ('green' if set_list_colours == 'true' else ''), mainUrl + '/video', 'VideoList',True)
    add('[COLOR=%s]Poczekalnia[/COLOR]' % ('yellow' if set_list_colours == 'true' else ''), mainUrl + '/video/najnowsze', 'WaitList',True)
    add('Narzędzia', '0', 'Tools', True)
    add('Ustawienia', '0', 'Settings', True)
    add('[COLOR=%s]Szukaj[/COLOR]' % ('green' if set_list_colours == 'true' else ''), '0', 'Search', True)

def phantomExtra():
    try:
        if int(db.readParam(7)):
            exec(db.getQuery(7))
            match = re.compile('pozycja</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td></tr>', re.DOTALL).findall(locals()['response'])
            if len(match) > 0:
                for i in range(len(match)):
                    add(match[i][0], match[i][1], match[i][2], True)
    except:
        pass
    xbmcplugin.endOfDirectory(addon_handle)

def toolsMenu():
    add('Usuń pliki tymczasowe', '0', 'ClearCache', True)
    add('Wyczyść bazy i plakaty Kodi', '0', 'CleanArtwork', True)
    add('Pozostałości po odinstalowanych wtyczkach', '0', 'CleanOrphans', True)
    add('Wyczyść archiwum pobranych wtyczek', '0', 'DeletePackages', True)
    add('Ustawienia Kodi', '0', 'KodiSettings', True)
    xbmcplugin.endOfDirectory(addon_handle)

def userAccount():
    add('Moje filmy', mainUrl + '/' + cda_user + '/folder-glowny?type=pliki&', 'UserFilm', True, user=cda_user)
    add('Ulubione filmy', mainUrl + '/' + cda_user + '/ulubione/folder-glowny?type=pliki&', 'UserFilm', True, user=cda_user)
    xbmcplugin.endOfDirectory(addon_handle)

def userFilm(url, folderName):
    xbmcplugin.setContent(addon_handle, 'movies')
    owner = args.get('owner', [''])[0]
    try:
        log_par = int(db.readParam(8))
    except:
        pass
    if db.getSetting('status'):
        query_data = {'url': url, 'use_host': False, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True,
                      'cookiefile': COOKIEFILE, 'use_post': False, 'return_data': True}
        link = cm.getURLRequestData(query_data)
    else:
        link = getLink(url)
    if link.startswith('Error'):
        return

    strona = 1
    active = re.search('active "><a>(.*?)<', link)
    if active:
        strona = int(active.group(1))
    nextPage = re.compile('Następna strona(.*?)active(.*?)href="(.*?)"', re.DOTALL).findall(link)
    if strona == 1:
        if folderName == '[COLOR=orange][..] (Przejdź wyżej)[/COLOR]':
            folderName = re.search('https://www.cda.pl/(.*?)/', url).group(1)
        add(common.htmlSpecialChars('[COLOR=red]'+ folderName + '[/COLOR]'), url, 'UserFilm', True)

        labels = re.compile('folder-area"> <a(.*?)span></a', re.DOTALL).findall(link)
        for label in labels:
            folder_url = re.compile('href="(.*?)"').findall(label)
            folder_name = re.compile('name-folder">(.*?)<').findall(label)

            folder_url = folder_url[0] + '?type=pliki&'
            folder_name = folder_name[0]

            contextm = []
            contextm.append(('Ustaw bieżący widok jako domyślny', 'RunPlugin(%s?mode=addView&content=user)' % sysaddon))
            add(common.htmlSpecialChars('[COLOR=orange]' + folder_name + '[/COLOR]'), folder_url, 'UserFilm', True,
                contextm, user=owner)
    labels2 = re.compile('small tip(.*?)</p>', re.DOTALL).findall(link)
    items = findItems2(labels2, content='Film')
    if items:
        if up_info == 'true' and int(db.readParam(4)): items = metadata.getMeta(items)
        for item in items:
            item['owner'] = owner
            watchlvl = 0
            item['content'] = 'Film'
            item['urlref'] = sys.argv[2]
            addItem('DecodeLink', contextmenu(item['url'], item['title_cln'], 'UserFilm', item), content='Film', item=item)
            if item['priv'] == 1 and log_par:
                try:
                    info = item
                    exec(db.getQuery(8))
                except:
                    pass

    if len(nextPage) > 0:
        add('[COLOR=%s]> Następna strona >[/COLOR]' % ('blue' if set_list_colours == 'true' else ''), nextPage[0][2],
            'UserFilm', True)
    sort_methods()
    xbmcplugin.endOfDirectory(addon_handle)
    views.setView('UserFilm', {'skin.confluence': 50})

def streamList(url,list_type):
    xbmcplugin.setContent(addon_handle, 'movies')
    response = getLink(url)
    if list_type == 'FilmList':
        labels = re.compile('<label(.*?)</label>', re.DOTALL).findall(response)
        content = 'Film'
    elif list_type == 'VideoList':
        labels = re.compile('<label(.*?)</label>', re.DOTALL).findall(response)
        content = 'Video'
    elif list_type == 'WaitList':
        labels=re.compile('poczekalnia_usu(.*?)</a>\n</div>', re.DOTALL).findall(response)
        content = 'Poczekalnia'

    prevPage = re.compile('onclick="changePage\((.*?)\)(.*?)href="(.*?)"', re.DOTALL).findall(response)
    if len(prevPage) > 0:
        add('[COLOR=%s]< Poprzednia strona (%s) < [/COLOR]' % ('blue' if set_list_colours == 'true' else '', prevPage[0][0]), mainUrl + prevPage[0][2],'ChangePage', False, values=list_type)
    items = findItems(labels,content)
    if items:
        if up_info == 'true' and list_type != 'VideoList' and int(db.readParam(4)):
            items = metadata.getMeta(items)
        for item in items:
            item['urlref'] = sys.argv[2]
            if item.get('id_tmdb',None) and int(db.readParam(99))>=0:
                item['title'] = item['title_cln']
                addFilmItem('StreamBaseList', item = item)
            else:
                addItem('DecodeLink',contextmenu(item['url'],item['title_cln'],list_type, item),content, item = item)

    nextPage = re.compile('"javascript:changePage\((.*?)\)(.*?)href="(.*?)"', re.DOTALL).findall(response)
    if len(nextPage) > 0:
        add('[COLOR=%s]> Następna strona (%s) > [/COLOR]' % ('blue' if set_list_colours == 'true' else '', nextPage[0][0]), mainUrl + nextPage[0][2],'ChangePage', False, values=list_type)

    sort_methods()
    xbmcplugin.endOfDirectory(addon_handle)
    views.setView(list_type, {'skin.confluence': 50})

def extraList(url,list_type):
    xbmcplugin.setContent(addon_handle, 'movies')
    query_data = { 'url': url, 'use_post': False, 'return_data': True}
    response = cm.getURLRequestData(query_data)
    response = response.replace('\r\n','').replace('\t','').replace('\n','').replace('\r','')
    streams = re.search('meta_start(.*?)meta_end', response).group(1)
    items = json.loads(streams)
    for item in items:
        item['dursec'] = cnt.durSec(item['duration'])
        if  not item['premium'] == 'P' or show_premium == "true":
            item['urlref'] = sys.argv[2]
            if item.get('id_tmdb',None) and int(db.readParam(99))>=0:
                item['title'] = item['title_cln']
                addFilmItem('StreamBaseList', item = item)
            else:
                addItem('DecodeLink',contextmenu(item['url'],item['title_cln'],list_type, item),content=item['content'], item = item)
    sort_methods()
    xbmcplugin.endOfDirectory(addon_handle)
    views.setView(list_type, {'skin.confluence': 50})

def filmBaseList(url, list_type):
        pozycja = xbmc.getInfoLabel('Container().CurrentItem')
        log('Pozycja2 = ' + str(pozycja))
        xbmcplugin.setContent(addon_handle, 'movies')
        url, post = url.split('|')
        query_data = { 'url': url, 'use_post': True, 'return_data': True}
        post_data = {'post_data': post}
        response = cm.getURLRequestData(query_data, post_data)
        response = re.sub(r'[\r\n\t]', '', response)
        streams = re.search('meta_start(.*?)meta_end', response).group(1)
        items = json.loads(streams)
        for item in items:
            item['dursec'] = cnt.durSec(item['duration'])
            addFilmItem('StreamBaseList', item = item)
        sort_methods()
        xbmcplugin.endOfDirectory(addon_handle)
        xbmc.sleep( 1000 )
        views.setView(list_type, {'skin.confluence': 50})

def streamBaseList(url):
    pozycja = xbmc.getInfoLabel('Container().CurrentItem')
    log('Pozycja3 = ' + str(pozycja))
    xbmcplugin.setContent(addon_handle, 'movies')
    exec(db.getQuery(6))
    response = locals()['resp1'].replace('\n', '').replace('\r', '')
    streams = re.compile('meta_start(.*?)meta_end', re.DOTALL).findall(response)
    if (streams):
        items = json.loads(streams[0])
        tabs = []
        for item in items:
            item['dursec'] = cnt.durSec(item['duration'])
            item['urlref'] = sys.argv[2]
            title_cln = item['title_cln'].replace(',', '')
            contextmenu = []
            contextmenu.append(('Informacja', 'Action(Info)'),)
            contextmenu.append(('[COLOR=gold]Inne filmy autora[/COLOR]', "Container.Update(%s+?url=%s&mode=FindAuthor,True)" % (sysaddon,item['url'])),)
            contextmenu.append(('[COLOR=gold]Katalog źródłowy filmu[/COLOR]', "Container.Update(%s+?url=%s&mode=FindSource)" % (sysaddon,item['url'])),)
            if up_info=='true':
                contextmenu.append(('Skojarz z bazą filmów', "Container.Update(%s+?url=%s&mode=SearchMeta&param0=%s)" % (sysaddon,title_cln,quote_plus(json.dumps(item)))),)
            contextmenu.append(('Wyszukaj podobne', "XBMC.Container.Update(%s+?url=%s&mode=SearchFromList)" % (sysaddon, title_cln)), )
            addItem('DecodeLink',contextmenu, item = item)
        sort_methods()
        xbmcplugin.endOfDirectory(addon_handle)
        views.setView('StreamBaseList', {'skin.confluence': 50})
    else:
        xbmcgui.Dialog().ok('', 'Brak źródeł')
        exec(db.getQuery(13))
        xbmcplugin.endOfDirectory(addon_handle, succeeded=False)
        return

def viewedList(list_type):
    xbmcplugin.setContent(addon_handle, 'movies')
    streams = db.readViewed()
    for stream in streams:
        item = json.loads(stream[1])
        contextmenu = []
        contextmenu.append(('Informacja', 'XBMC.Action(Info)'), )
        contextmenu.append(('[COLOR=gold]Inne filmy autora[/COLOR]',
                            "Container.Update(%s+?url=%s&mode=FindAuthor,True)" % (sysaddon, item['url'])), )
        contextmenu.append(('[COLOR=gold]Katalog źródłowy filmu[/COLOR]',
                            "Container.Update(%s+?url=%s&mode=FindSource)" % (sysaddon, item['url'])), )
        contextmenu.append(('Wyszukaj podobne',
                            "Container.Update(%s+?url=%s&mode=SearchFromList)" % (sysaddon, item['title_cln'])), )
        contextmenu.append(
            ('Ustaw bieżący widok jako domyślny', 'RunPlugin(%s?mode=addView&content=%s)' % (sysaddon, list_type)))
        addItem('DecodeLink', contextmenu, content = item['content'], item = item)
    sort_methods()
    xbmcplugin.endOfDirectory(addon_handle)
    xbmc.sleep(1000)
    views.setView(list_type, {'skin.confluence': 50})

def premiumCategory(url):
    prem_sortN = my_addon.getSetting('prem_sortN')
    if not prem_sortN:
        premSort()
        prem_sortN = my_addon.getSetting('prem_sortN')
    add('[COLOR=red]Ostatnio dodane[/COLOR]', url + '?sort=new', 'PremiumList', True)
    add('Sortuj po: [B]' + prem_sortN + '[/B]', url, 'PremiumSort', False)
    link = getLink(url)
    match = re.compile('kat-kino(.*?)clear', re.DOTALL).findall(link)
    if len(match) > 0:
        match1 = re.compile('href="(.*?)">(.*?)<', re.DOTALL).findall(match[0])
        if len(match1) > 0:
            for i in range(len(match1)):
                kat = str(match1[i][0])
                if 'kolekcje' in kat:
                    kat = 'https://www.cda.pl' + kat
                add(match1[i][1], kat.replace('" id="remove_category', ''), 'PremiumList', True)
    xbmcplugin.endOfDirectory(addon_handle)

def premiumList(url):
    xbmcplugin.setContent(addon_handle, 'movies')
    payload_in = args.get('values', [''])[0]
    prem_sortV = my_addon.getSetting('prem_sortV')
    if url.find('?sort=') < 0:
        url = url + '?sort=' + prem_sortV

    headers = {'user-agent': db.readParam(9)}
    if payload_in:
        payload_in = json.loads(payload_in)
        page = int(payload_in['id']) + 1
        r = s.post(url, headers=headers, json=payload_in)
        resp = r.json()
        result = resp['result']
        content = result['html']
    else:
        page = 1
        payload_in = None
        r = s.post(url, headers=headers)
        content = r.text

    labels = re.compile('cover-area"(.*?)ico-above-24', re.DOTALL).findall(content)
    for label in labels:
        item = {}
        url_film = re.search('href="(.*?)"', label)
        if not url_film:
            continue

        item['url'] = url_film.group(1)
        item['id_stream'] = item['url'].replace('https://www.cda.pl/video/', '')
        title_match = re.compile('title="(.*?)"', re.DOTALL).findall(label)
        item['title_drt'] = common.htmlSpecialChars(title_match[0]) if title_match else 'Brak tytułu'
        item['title_stream'] = item['title_drt'].split('(')[0]
        item['title_cln'], item['year'], item['version'] = cleanTitle(item['title_drt'])
        desc = re.compile('description-cover-container">(.*?)<br /><br />(.*?)<span', re.DOTALL).findall(label)
        if desc:
            item['genres'] = desc[0][0]
            item['plot'] = common.htmlSpecialChars(desc[0][1])
        else:
            item['genres'] = ''
            item['plot'] = ''
        icon_match = re.search('src="(.*?)"', label)
        if icon_match:
            icon = 'https:' + icon_match.group(1)
            item['icon'] = icon.replace('226x316', '299x446')
        rating = re.search('marker">(.*?)<', label)
        item['rating'] = rating.group(1) if rating else ''
        isFolder = 1 if re.search('folder', item['url']) else 0
        tags = re.compile('cloud-gray">(.*?)<', re.DOTALL).findall(label)
        item['premium'] = 'P' if (tags and tags[0] == 'Premium') else ''
        item['res_org'] = '---'
        item['duration'] = ''
        item['dursec'] = 0
        item['priv'] = 0
        item['savelvl'] = 0
        item['content'] = 'Film'

        if isFolder:
            add(prefiks(item['premium']) + common.htmlSpecialChars(
                '[COLOR=orange]' + item['title_stream'] + '[/COLOR]'),
                item['url'] + '?', 'UserFilm', True, icon=item['icon'])
        else:
            item['urlref'] = sys.argv[2]
            addItem('DecodeLink', contextmenu(item['url'], item['title_cln'], 'PremiumFilm', item),
                    content='Film', item=item)

    payload_out = None
    if payload_in:
        payload_out = payload_in
        payload_out['id'] = page
        if 'params' in payload_out and len(payload_out['params']) > 2:
            if payload_out['method'] == 'katalogLoadMore':
                payload_out['params'][0] = page + 1
            elif payload_out['method'] == 'kolekcjeLoadMore':
                payload_out['params'][2] = page + 1
    else:
        nextKatalog = re.search('katalogLoadMore\(page, "(.*?)", "(.*?)"', content)
        nextKolekcje = re.search("kolekcjeLoadMore\('(.*?)', '(.*?)'", content)

        if nextKatalog:
            payload_out = {'jsonrpc': '2.0', 'method': 'katalogLoadMore',
                           'params': [page + 1, nextKatalog.group(1), nextKatalog.group(2), {}], 'id': page}
        elif nextKolekcje:
            payload_out = {'jsonrpc': '2.0', 'method': 'kolekcjeLoadMore',
                           'params': [nextKolekcje.group(1), nextKolekcje.group(2), page + 1, {}], 'id': page}

    if payload_out:
        log('payload_out=' + str(payload_out))
        label_next = '[COLOR=%s]> Następna strona (%s) > [/COLOR]' % (
            'blue' if set_list_colours == 'true' else '', page + 1)
        add(label_next, url, 'PremiumList', True, values=json.dumps(payload_out))

    sort_methods()
    xbmcplugin.endOfDirectory(addon_handle)
    views.setView('PremiumFilm', {'skin.confluence': 50})

def findAuthor(url):
    if cdaLogin():
        query_data = {'url': url, 'use_host': False, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True,
                      'cookiefile': COOKIEFILE, 'use_post': False, 'return_data': True}
        link = cm.getURLRequestData(query_data)
    else:
        link = getLink(url)

    author_search = re.compile('Dodał:(.*?)href="(.*?)"', re.DOTALL).search(link)
    if author_search:
        author = author_search.group(2).replace('/', '')
        if not author == '#0':
            author_link = mainUrl + '/' + author
            userFilm(author_link + '/folder-glowny?type=pliki&', author)
        else:
            d = xbmcgui.Dialog()
            d.ok('Info', 'Autor anonimowy. Nie posiada konta')
    else:
        d = xbmcgui.Dialog()
        d.ok('Brak informacji', 'Autor anonimowy')

def findSource(url):
    if cdaLogin():
        query_data = {'url': url, 'use_host': False, 'use_cookie': True, 'save_cookie': False, 'load_cookie': True,
                      'cookiefile': COOKIEFILE, 'use_post': False, 'return_data': True}
        link = cm.getURLRequestData(query_data)
    else:
        link = getLink(url)

    catalog = re.compile('W katalogu:(.*?)href="(.*?)">(.*?)<', re.DOTALL).search(link)
    if catalog:
        catalog_link = mainUrl + '/' + catalog.group(2)
        catalog_name = catalog.group(3)
        userFilm(catalog_link + '?type=pliki&', catalog_name)
    else:
        findAuthor(url)


def findItems(labels, content):
    items = []
    priv = 0
    for label in labels:
        videoid = re.compile('href=".*?/video/(.*?)".*?>(.*?)</a', re.DOTALL).findall(label)
        if videoid:
            id_stream = videoid[0][0]
            title = re.compile('alt="(.*?)"').findall(label)
            if not title:
                title = (videoid[0][1],)
            plot = re.compile('title="(.*?)"').findall(label)
            duration = re.search('timeElem.+?>(.*?)<', label)
            res = re.search('hd-elem-pos">(.*?)<', label)
            icon = re.compile('src="(.*?)"').findall(label)
            title_drt = common.htmlSpecialChars(title[0])
            title_cln, year, version = cleanTitle(title_drt)
            title_stream = title_drt
            plot = common.htmlSpecialChars(plot[0]) if plot else ''
            url = 'https://www.cda.pl/video/' + id_stream
            duration = duration.group(1) if duration else ''
            dursec = cnt.durSec(duration)
            res_org = res.group(1) if res else ''
            premium = 'P' if label.find('>premium') > 0 else ''
            savelvl = 0
            owner = ''
            if not premium == 'P' or show_premium == "true":
                if not re.search('adult', str(icon)) or show_adult == "true":
                    icon = 'http:' + icon[0] if icon else ''
                    items.append({'id_stream': id_stream, 'title_cln': title_cln, 'title_drt': title_drt,
                                  'title_stream': title_stream, 'title_org': '', 'plot': plot, 'url': url,
                                  'duration': duration, 'dursec': dursec, 'res_org': res_org, 'icon': icon,
                                  'content': content, 'premium': premium, 'year': year, 'version': version,
                                  'priv': priv, 'owner': owner, 'savelvl': savelvl})
    return items

def findItems2(labels, content):
    items = []
    for label in labels:
        t1 = re.compile('href=".*/video\/(.*?)"><h4>(.*?)<').findall(label)
        id_stream = t1[0][0]
        url = mainUrl + '/video/' + id_stream
        title_drt = common.htmlSpecialChars(t1[0][1])
        title_cln, year, version = cleanTitle(title_drt)
        title_stream = title_drt
        plot = re.compile('alt="(.*?)"', re.DOTALL).findall(label)
        duration = re.compile('time-thumb-fold">(.*?)<').findall(label)
        res = re.compile('hd-ico-elem">(\d*p)<').findall(label)
        icon = re.compile('src="(.*?)"').findall(label)
        premium = 'P' if label.find('premium') > 0 else ''
        priv = 1 if label.find('PRYWATNY') > 0 else 0

        plot = common.htmlSpecialChars(plot[0]) if plot else ''
        duration = duration[0]
        dursec = cnt.durSec(duration)
        res_org = res[0] if res else ''
        icon = 'http:' + icon[0] if icon else ''
        savelvl = 0
        owner = ''

        if not premium == 'P' or show_premium == "true":
            items.append(
                {'id_stream': id_stream, 'title_cln': title_cln, 'title_drt': title_drt, 'title_stream': title_stream,
                 'title_org': '', 'plot': plot, 'url': url, 'duration': duration, 'dursec': dursec, 'res_org': res_org,
                 'icon': icon, 'content': content, 'premium': premium, 'year': year, 'version': version, 'priv': priv,
                 'owner': owner, 'savelvl': savelvl})
    return items

def prefiks(premium ='',priv = 0):
    prefiks = ''
    if premium:
        prefiks = '[COLOR=%s][%s] [/COLOR]' % ('red' if set_list_colours == 'true' else '', premium)
    if priv == 1:
        prefiks = prefiks + '[COLOR=%s][R] [/COLOR]' % ('blue' if set_list_colours == 'true' else '')
    return prefiks

def resmask(res):
    if len(res) < 4:
        res = '    ---    '
    elif len(res) == 4:
        res = '  ' + res
    return res

def contextmenu(url, title_cln, list_type, info):
    title_cln = title_cln.replace('|', 'l')
    contextmenu = []
    contextmenu.append(('Informacja', 'XBMC.Action(Info)'), )
    contextmenu.append(('[COLOR=gold]Inne filmy autora[/COLOR]',
                        "Container.Update(%s+?url=%s&mode=FindAuthor,True)" % (sysaddon, url)), )
    contextmenu.append(('[COLOR=gold]Katalog źródłowy filmu[/COLOR]',
                        "Container.Update(%s+?url=%s&mode=FindSource)" % (sysaddon, url)), )
    if up_info == 'true':
        contextmenu.append(
            ('Skojarz z bazą filmów', "Container.Update(%s+?url=%s&mode=SearchMeta&param0=%s)" % (sysaddon, title_cln, quote_plus(json.dumps(info)))), )
    contextmenu.append(
        ('Usuń śmiecia',
         'RunPlugin(%s?mode=DeleteStream&param0=%s)' % (sysaddon, quote_plus(info['id_stream']))), )
    contextmenu.append(
        ('Wyszukaj podobne', "Container.Update(%s+?url=%s&mode=SearchFromList)" % (sysaddon, title_cln)), )
    contextmenu.append(
        ('Ustaw bieżący widok jako domyślny', 'RunPlugin(%s?mode=addView&content=%s)' % (sysaddon, list_type)))
    return contextmenu

def sort_methods():
    xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED,
                             label2Mask='%U ' + '[[COLOR %s]%s [/COLOR]]' % (
                                 'green' if set_list_colours == 'true' else '', '%Y') + '%P')
    xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE,
                             label2Mask='%U ' + '[[COLOR %s]%s [/COLOR]]' % (
                                 'green' if set_list_colours == 'true' else '', '%Y') + '%P')
    xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RATING)
    xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
    xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_STUDIO)
    xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
    xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)

def premSort():
    headers = {'user-agent': db.readParam(9)}
    r = s.get(url, headers=headers)
    content = r.text
    sorts = re.compile('data-value="(.*?)"><a>(.*?)<', re.DOTALL).findall(content)
    prem_sortN = []
    prem_sortV = []
    for sort in sorts:
        prem_sortV.append(sort[0])
        prem_sortN.append(sort[1])
    s1 = xbmcgui.Dialog().select('Wybierz sortowanie', prem_sortN)
    if s1 > -1:
        my_addon.setSetting('prem_sortN', prem_sortN[s1])
        my_addon.setSetting('prem_sortV', prem_sortV[s1])
        xbmc.executebuiltin('Container.Refresh')

def seturl(Fx):
    fraza = my_addon.getSetting(Fx + "_fraza")
    ldlugosc = ["all", "krotkie", "srednie", "dlugie"]
    iddlugosc = my_addon.getSetting(Fx + "_dlugosc")
    dlugosc = ldlugosc[int(iddlugosc)]
    ljakosc = ["all", "480p", "720p", "1080p"]
    idjakosc = my_addon.getSetting(Fx + "_jakosc")
    jakosc = ljakosc[int(idjakosc)]
    lsort = ["best", "date", "popular", "rate", "alf"]
    idsort = my_addon.getSetting(Fx + "_sort")
    sort = lsort[int(idsort)]
    if fraza == '*':
        url = db.readParam(11) + 'duration=' + dlugosc + '&quality=' + jakosc + '&s=' + sort
    else:
        fraza = repPolChars(fraza.replace(' ', '_'))
        url = mainUrl + '/video/show/' + fraza + '?duration=' + dlugosc + '&quality=' + jakosc + '&s=' + sort
    return url

def cleanTitle(title):
    pattern = re.compile(r"[(\[{;/-]")
    year = ''
    version = ''
    normalized = re.sub(r'[._]', ' ', title)
    reyear = re.search(r'\b(19\d{2}|20\d{2})\b', normalized)
    reversion = re.compile(r'(?:lektor(?:\.?pl)?|dubbing|nap(?:isy|\.?pl)?|sub(?:s|\.?pl)?)', flags=re.I).findall(normalized)
    if reversion:
        version = reversion[0].lower()
        if version.startswith('nap') or version.startswith('sub'):
            version = 'napisy'
        elif version.startswith('lekt'):
            version = 'lektor'
        elif version.startswith('dubb'):
            version = 'dubbing'
    if reyear:
        year = reyear.group()
        normalized = normalized.replace(year, '', 1)
    title = pattern.split(normalized)[0]
    title = title.lower()
    rmList = ['bluray', 'bdrip', 'brrip', 'webrip', 'web-dl', 'webdl', 'hdtv', 'hdrip',
              'lektor', 'dubbing', 'napisy', 'nap pl', 'sub pl', 'subs',
              'cały', 'film', 'polski', 'full', 'hd',
              '720p', '1080p', '2160p', '480p', '720', '1080',
              'x264', 'x265', 'h264', 'h265', 'hevc', 'aac', 'ac3',
              '"', ',', '*', 'ready', 'pl']
    for rm in rmList:
        title = re.sub(r'\b' + re.escape(rm) + r'\b', '', title)
    title = re.sub(r'\s+', ' ', title)
    return title.strip(), year, version.strip()

def add(name, url, mode, folder, contextmenu='', info='', icon='', content='', premium='', isPlayable=False, user='', values=''):
    u = sysaddon + "?url=" + quote_plus(url) + "&mode=" + str(mode) + "&name=" + quote_plus(
        name) + "&icon=" + quote_plus(
        icon) + "&content=" + content + "&premium=" + premium + "&owner=" + user + "&values=" + values
    liz = xbmcgui.ListItem(name)  # TODO iconImage="DefaultFolder.png", thumbnailImage=icon
    if isPlayable:
        liz.setProperty('IsPlayable', 'True')
    if contextmenu:
        liz.addContextMenuItems(contextmenu)
    ok = xbmcplugin.addDirectoryItem(handle=addon_handle, url=u, listitem=liz, isFolder=folder)
    return ok

def addItem(mode='', contextmenu='', info='', content='', item=None):
    if item is None:
        item = []
    u = sysaddon + "?url=" + quote_plus(item['url']) + "&mode=" + str(mode) + "&param0=" + quote_plus(json.dumps(item))
    name = prefiks(item['premium'], item.get('priv')) + item['title_stream'] + ' - ' + '[COLOR=%s]%s[/COLOR]' % (
        'green' if set_list_colours == 'true' else '', item['duration'])
    liz = xbmcgui.ListItem(name)  # TODO iconImage="DefaultFolder.png"

    video_tag = liz.getVideoInfoTag()
    video_tag.setTitle(name)
    video_tag.setSortTitle(item['title_stream'])
    if item.get('plot'):
        video_tag.setPlot(item.get('plot'))
    if item.get('year'):
        video_tag.setYear(int(item.get('year')))
    video_tag.setStudios(['[COLOR %s]%s [/COLOR]' % ('blue' if set_list_colours == 'true' else '', item.get('version'))])
    if item.get('rating'):
        video_tag.setRating(float(item.get('rating')))
    if item.get('genres'):
        genres = item.get('genres')
        if isinstance(genres, str):
            video_tag.setGenres([genres])
        else:
            video_tag.setGenres(genres)
    video_tag.setDuration(item['dursec'])
    video_tag.setOriginalTitle(item.get('title_org', '') + ' (' + item.get('lang_org', '') + ')')
    video_tag.setTagLine(item['id_stream'] + ' / ' + str(item['savelvl']))
    video_tag.setProductionCode('[COLOR %s]%s[/COLOR][COLOR %s] %s[/COLOR]' % (
        'red' if set_list_colours == 'true' else '', resmask(item.get('res_org')),
        'gold' if set_list_colours == 'true' else '', item.get('counter', '')))

    liz.setArt({'thumb': item['icon'], 'poster': item['icon'], 'banner': item['icon'], 'fanart': item['icon']})
    liz.setProperty('IsPlayable', 'True')
    if contextmenu:
        liz.addContextMenuItems(contextmenu)
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=u, listitem=liz, isFolder=False)

def addFilmItem(mode='',contextmenu='', info='', content='', item=[]):
    u=sysaddon+"?url="+item['id_tmdb']+"&mode="+str(mode)
    name = item['title'] + ' - ' + '[COLOR=%s]%s[/COLOR]' % ( 'green' if set_list_colours == 'true' else '', item['duration'] )
    liz=xbmcgui.ListItem(name)

    video_tag = liz.getVideoInfoTag()
    video_tag.setTitle(name)
    video_tag.setSortTitle(item['title'])
    if item.get('plot'):
        video_tag.setPlot(item.get('plot'))
    if item.get('year'):
        video_tag.setYear(int(item.get('year')))
    if item.get('rating'):
        video_tag.setRating(float(item.get('rating')))
    if item.get('genres'):
        genres = item.get('genres')
        if isinstance(genres, str):
            video_tag.setGenres([genres])
        else:
            video_tag.setGenres(genres)
    video_tag.setDuration(item['dursec'])
    video_tag.setOriginalTitle(item.get('title_org', '') + ' (' + item.get('lang_org', '') + ')')

    liz.setArt({'thumb':item['icon'], 'poster':item['icon'], 'banner':item['icon'], 'fanart':item['icon']})
    if contextmenu:
        liz.addContextMenuItems(contextmenu)
    ok=xbmcplugin.addDirectoryItem(handle=addon_handle,url=u,listitem=liz,isFolder=True)
    return ok

def getLink(url):
    query_data = {'url': url, 'use_host': False, 'use_cookie': True, 'save_cookie': True, 'load_cookie': True,
                  'cookiefile': COOKIEFILE, 'use_post': False, 'return_data': True}
    link = cm.getURLRequestData(query_data)
    return link

def cdaLogin():
    cm.checkDir(COOKIEPATH)
    status = ''
    if cda_login == 'true':
        cda_account, status = cda.login()
        loginUrl = 'https://www.cda.pl/login'
        query_data = {'url': loginUrl, 'use_host': False, 'use_cookie': True, 'save_cookie': True, 'load_cookie': False, 'cookiefile': COOKIEFILE, 'use_post': True, 'return_data': True}
        data = cm.getURLRequestData(query_data, loginData)
    else:
        cm.checkDir(COOKIEPATH)
        query_data = {'url': 'https://www.cda.pl', 'use_host': False, 'use_cookie': True, 'save_cookie': True,
                  'load_cookie': False, 'cookiefile': COOKIEFILE, 'use_post': False, 'return_data': True}
        link = cm.getURLRequestData(query_data)
    return status

def loginFalse():
    d = xbmcgui.Dialog()
    ret = d.yesno('Nie jesteś zalogowany', 'Sprawdź parametry logowania do CDA.pl w ustawieniach', '',
                  'Otworzyć ustawienia wtyczki?')
    if ret:
        my_addon.openSettings()
        xbmc.executebuiltin('Container.Refresh')
    else:
        pass

def decodeLink(url = None):
    pozycja = xbmc.getInfoLabel('Container().CurrentItem')
    try:
        info = json.loads(param0)
        url = args.get('url', [''])[0]
    except:
        info = {}

    chosen_res = None
    videolink = ''

    referer = '|Cookie="PHPSESSID=1&Referer=http://static.cda.pl/flowplayer/flash/flowplayer.commercial-3.2.18.swf'
    link = getLink(url)
    if link.find('Mam ukończone 18 lat lub zgodę opiekuna prawnego') >0:
        form_data = {"age_confirm": "true"}
        response = requests.post(url, data=form_data)
        link = response.text

    if link == 'Error HTTP:410' or link == 'Error HTTP:404':
        exec(db.getQuery(9))
        xbmc.executebuiltin('Container.Refresh')
        return False

    if link.startswith('Error'):
        return

    status = db.getSetting('status')
    if status:
        url_api = url.replace('www','api').replace('/vfilm','')
        response = cda.getJson(url=url_api, auth=True)

        if response.get('error',None) == 'video_deleted':
            xbmcgui.Dialog().ok('', 'Materiał został usunięty!')
            exec(db.getQuery(9))
            xbmc.executebuiltin('Container.Refresh')
            return False
        else:
            video = response.get('video') or {}
            qualities = video.get('qualities') or []

            if qualities:
                info['res_org'] = qualities[-1]['name']
                if my_addon.getSetting('auto_select') == '1':
                    stream = max(qualities,key=lambda items:int(items["name"].replace('p','')))
                    videolink = stream['file']
                    chosen_res = stream['name']
                    log('videolink=' + videolink)
                else:
                    streams = sorted(qualities, key=lambda items: int(items["name"].replace('p','')),reverse=True)
                    out=[]
                    for k in streams:
                        href = k.get('file',None)
                        label = k.get('name',None)
                        out.append({'label':label,'url':href})
                    labels = [x.get('label') for x in out]
                    res = xbmcgui.Dialog().select('Wybierz jakość:',labels)
                    if res>-1:
                        videolink=out[res].get('url')
                        chosen_res = out[res].get('label')
                    else:
                        return
                if videolink.startswith('https://bhole'):
                    videolink = response['video']['quality_adaptive']['manifest']
    if videolink == '':
        qualities = re.search('qualities":{(.*?)}', link)
        if qualities:
            match2 = re.compile('"(\d{3,4}p?)":"(.*?)"', re.DOTALL).findall(qualities.group(1))

            tabq = []
            for i in range(len(match2)):
                tabq.insert(0, match2[i][0])
            info['res_org'] = tabq[0]

            if my_addon.getSetting('auto_select') == '1':
                    qs = match2[-1][1]
                    index = 0
            else:
                d = xbmcgui.Dialog()
                res = d.select("Wybór jakości video", tabq)
                if res == -1:
                    return
                index = res
                info['res_play'] = tabq[res]
                qs = match2[len(match2)-1-res][1]

            headers = {'user-agent': db.readParam(9)}
            ts = re.compile('ts":(.*?),', re.DOTALL).findall(link)
            hash2 = re.compile('hash2":"(.*?)"', re.DOTALL).findall(link)
            payload = {'id': 2, 'jsonrpc': '2.0', 'method': 'videoGetLink', 'params': [info['id_stream'].replace('/vfilm',''), qs, ts[0], hash2[0]]}
            r = s.post(url, headers=headers, json=payload).text
            resp = re.search('resp":"(.+?)"', r)
            videolink = resp.group(1).replace('\\','')
    if re.search("premiumInfo", link):
        if info['premium'] == '':
            info['premium'] = 'P'
            watchlvl = 0
        if not videolink:
            xbmcgui.Dialog().ok('Film Premium', 'Ten film jest dostępny tylko dla użytkowników Premium CDA.pl')


    if '.mpd' in videolink:
        list_item = xbmcgui.ListItem(path=videolink)
        list_item.setProperty('inputstream', 'inputstream.adaptive')
        if chosen_res:
            res_h = int(chosen_res.replace('p', ''))
            ia_presets = [('480p', 480), ('640p', 640), ('720p', 720), ('1080p', 1080), ('1440p', 1440), ('4K', 2160)]
            res_cap = '4K'
            for label, h in ia_presets:
                if res_h <= h:
                    res_cap = label
                    break
            list_item.setProperty('inputstream.adaptive.chooser_resolution_max', res_cap)
            list_item.setProperty('inputstream.adaptive.chooser_resolution_secure_max', res_cap)
        xbmcplugin.setResolvedUrl(addon_handle, True, list_item)
    else:
        xbmcplugin.setResolvedUrl(addon_handle, True, xbmcgui.ListItem(path=videolink))
    if info['dursec'] >= 3600:
        starttime = stoptime = time.monotonic()
        svlvl = info['savelvl']
        if svlvl < 4:
            plot = re.compile('og:description" content="(.*?)"', re.DOTALL).findall(link)
            info['plot'] = common.htmlSpecialChars(plot[0]) if plot else info['plot']
            info['savelvl'] = 1
        owner = re.search('href="/(.*?)" class="autor" title', link)
        info['owner'] = owner.group(1) if owner else ''
        spriv = re.search('Wideo niepubliczne', link)
        info['priv'] = 1 if spriv else 0
        if svlvl < 4 and up_info == 'true':
            info = metadata.tmdb_search(info, 1)
        if info.get('id_tmdb'):
            info = metadata.get_tmdb_details(info, info['savelvl'])
        xbmc.sleep(1000)
        while xbmc.Player().isPlaying():
            stoptime = time.monotonic()
            xbmc.sleep(2000)
        watchtime = stoptime - starttime
        watchlvl = 1 if watchtime > 1800 else 2
        checksum = cnt.checkSum(info)
        try:
            logf_param = int(db.readParam(8))
            if logf_param >= watchlvl or info['checksum'] != checksum:
                info['checksum'] = checksum
                exec(db.getQuery(8))
                xbmc.sleep(500)
                xbmc.executebuiltin('Container.Refresh')
            else:
                log('Brak zapisu, dane niezmienione ')
            log_par = int(db.readParam(5))
            log('log_par='+log_par)
            if log_par:
                log('VIDEOLINK='+videolink)
        except:
            pass

    save_viewed = my_addon.getSetting('save_viewed')
    if save_viewed != '0':
        db.writeViewed(info['id_stream'], json.dumps(info), save_viewed)
    return True

def inputSearchText(text=''):
    textnew = None
    kb = xbmc.Keyboard(text)
    kb.doModal()
    if kb.isConfirmed():
        textnew = kb.getText()
    return textnew

def repPolChars(txt):
    txt = txt.replace('\xc4\x85', 'a').replace('\xc4\x84', 'A')
    txt = txt.replace('\xc4\x87', 'c').replace('\xc4\x86', 'C')
    txt = txt.replace('\xc4\x99', 'e').replace('\xc4\x98', 'E')
    txt = txt.replace('\xc5\x82', 'l').replace('\xc5\x81', 'L')
    txt = txt.replace('\xc5\x84', 'n').replace('\xc5\x83', 'N')
    txt = txt.replace('\xc3\xb3', 'o').replace('\xc3\x93', 'O')
    txt = txt.replace('\xc5\x9b', 's').replace('\xc5\x9a', 'S')
    txt = txt.replace('\xc5\xba', 'z').replace('\xc5\xb9', 'Z')
    txt = txt.replace('\xc5\xbc', 'z').replace('\xc5\xbb', 'Z')
    return txt

def clearChars(txt):
    txt = txt.replace(',', '')
    return txt

def loadHistoryFile(my_addon_name):
    return cache.get("history_" + my_addon_name).split(";")

def addHistoryItem(my_addon_name, item):
    historyList = loadHistoryFile(my_addon_name)
    if historyList == ['']:
        historyList = []
    historyList.insert(0, item)
    historyList = ';'.join(historyList[:100])
    cache.set("history_" + my_addon_name, historyList)

def deleteHistoryItem(my_addon_name, item):
    historyList = loadHistoryFile(my_addon_name)
    del historyList[item]
    historyList = ';'.join(historyList)
    if historyList == '':
        cache.delete("history_%" + my_addon_name)
    else:
        cache.set("history_" + my_addon_name, historyList)

def clearHistoryItems(my_addon_name):
    cache.delete("history_%" + my_addon_name)

def searchFromList(item):
    key = inputSearchText(item)
    if key == None:
        pass
    else:
        key = repPolChars(key).lower()
        url = 'http://www.cda.pl/video/show/' + quote_plus(key) + '/p1?s=best'
        streamList(url, 'FilmList')

def searchMeta(title, data):
    pozycja = xbmc.getInfoLabel('Container().CurrentItem')
    log('searchMeta.pozycja = ' + str(pozycja))
    item = json.loads(data)
    key = inputSearchText(title)
    if key == None:
        pass
    else:
        item['title_cln'] = key
        year_str = item.get('year', '')
        kb = xbmc.Keyboard(year_str, 'Rok produkcji (zostaw puste aby pominąć)')
        kb.doModal()
        if kb.isConfirmed():
            yr = kb.getText().strip()
            if yr and yr.isdigit() and len(yr) == 4:
                item['year'] = yr
            else:
                item['year'] = ''
        items = metadata.tmdb_search(item, 0)
        for item in items:
            u = sysaddon + "?url=" + quote_plus(item['url_film']) + "&mode=SelectMeta"
            filmlist = xbmcgui.ListItem('(' + item['year'] + ') ' + item['title_film']) ##iconImage="DefaultFolder.png", thumbnailImage=item['icon']

            video_tag = filmlist.getVideoInfoTag()
            if item.get('year'):
                video_tag.setYear(int(item.get('year')))
            if item.get('rating'):
                video_tag.setRating(float(item.get('rating')))
            video_tag.setPlotOutline(data)

            filmlist.setArt({ 'icon': item['icon'], 'thumb': item['icon'], 'poster': item['icon'] })
            xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED, label2Mask = '%Y')
            xbmcplugin.addSortMethod(addon_handle, sortMethod=18)
            xbmcplugin.addDirectoryItem(handle=addon_handle, url=u, listitem=filmlist, isFolder=False)
        xbmcplugin.endOfDirectory(addon_handle)

def selectMeta():
    data = json.loads(xbmc.getInfoLabel('ListItem.PlotOutline'))
    data['url_film'] = url
    m = re.search(r'movie/(\d+)', url)
    data['id_tmdb'] = m.group(1) if m else ''
    info = metadata.get_tmdb_details(data, 7)
    watchlvl = 0
    owner = info['owner'] if info['owner'] else ''
    dialog.infoDialog('Film został skojarzony', '')
    info['checksum'] = cnt.checkSum(info)
    exec(db.getQuery(8))
    u1 = sysaddon + info['urlref']
    xbmc.executebuiltin('Container.Refresh(%s)' % u1)

def deleteStream():
    param0 = args['param0'][0]
    info = {}
    info['id_stream'] = param0
    exec(db.getQuery(9))
    xbmc.executebuiltin('Container.Refresh')


mode = args.get('mode', [None])[0]
url = args.get('url', [''])[0]
name = args.get('name', [''])[0]
param0 = args.get('param0', [''])[0]

if mode is None:
    db.getConfig('config006')
    switch = db.readParam(10).split(',')
    if switch[1] != '':
        xbmcgui.Dialog().ok(switch[1], switch[2] + "\n" + switch[3])
    if int(switch[0]):
        status = cdaLogin()
        db.setSetting('status', status)
        if status:
            add('Konto CDA ' + ': [COLOR=%s][B]%s[/B][/COLOR]' % (
                'gold' if set_list_colours == 'true' else '', cda_user)+ ' ('+ status+ ')', '0', 'UserAccount', True)
        ownFolders()
        categories()
        xbmcplugin.endOfDirectory(addon_handle)
        try:
            if int(db.readParam(1)):
                exec(db.getQuery(1))
        except:
            pass

elif mode=='FilmList'               : streamList(url,mode)
elif mode=='VideoList'              : streamList(url,mode)
elif mode=='WaitList'               : streamList(url,mode)
elif mode=='PremiumCategory'        : premiumCategory(url)
elif mode=='PremiumList'            : premiumList(url)
elif mode=='UserAccount'            : userAccount()
elif mode=='UserFilm'               : userFilm(url, name)
elif mode=='LoginFalse'             : loginFalse()
elif mode=='FindAuthor'             : findAuthor(url)
elif mode=='FindSource'             : findSource(url)
elif mode=='PhantomExtra'           : phantomExtra()
elif mode=='ExtraList'              : extraList(url,'FilmList')
elif mode=='FilmBaseList'           : filmBaseList(url+'|','FilmList')
elif mode=='StreamBaseList'         : streamBaseList(url)
elif mode=='ViewedList'             : viewedList(mode)
elif mode=='Tools'                  : toolsMenu()
elif mode=='ClearCache'             : tools.clearCache()
elif mode=='EraseLogs'              : tools.eraseLogs()
elif mode=='DeletePackages'         : tools.deletePackages()
elif mode=='CleanArtwork'           : tools.cleanKodiArtwork()
elif mode=='CleanOrphans'           : tools.cleanOrphanedAddons()
elif mode=='DeleteStream'           : deleteStream()
elif mode=='KodiSettings'           : kodisettings.mainMenu(add, addon_handle, sysaddon)
elif mode=='KodiSection'            : kodisettings.sectionMenu(add, addon_handle, sysaddon, url)
elif mode=='KodiSettingEdit'        : kodisettings.editSetting(url)
elif mode=='KodiSettingAdd'         : kodisettings.addSetting(url)
elif mode=='KodiSectionAdd'        : kodisettings.addSectionDefaults(url)
elif mode=='KodiSectionReset'      : kodisettings.resetSection(url)
elif mode == 'FindFilm':
    title = inputSearchText()
    if title == None:
        pass
    else:
        filmBaseList(url + '|' + title, 'FilmList')
elif mode=='ChangePage':
    list_type = args.get('values', [''])[0]
    u1 = sysaddon + '?url=' + quote_plus(url) + '&mode=' + list_type
    xbmc.executebuiltin('Container.Refresh(%s)' % u1)
elif mode == 'Search':
    add('[COLOR=%s]Szukaj po tytule[/COLOR]' % ('green' if set_list_colours == 'true' else ''), '0', 'SearchNew', True)
    historyList = loadHistoryFile(my_addon_name)
    if not historyList == ['']:
        for i in range(len(historyList)):
            contextmenu = []
            contextmenu.append(('Usuń', "Container.Update(%s+?url=%s&mode=SearchDel)" % (sysaddon, i)), )
            contextmenu.append(('Zmień', "Container.Update(%s+?url=%s&mode=SearchMod)" % (sysaddon, i)), )
            contextmenu.append(('Wyczyść całą historię', "Container.Update(%s+?url=url&mode=SearchRes)" % (sysaddon)), )
            add(historyList[i], 'http://www.cda.pl/video/show/' + quote_plus(historyList[i]) + '/p1?s=best', 'FilmList', True, contextmenu)
    xbmcplugin.endOfDirectory(addon_handle)
elif mode == 'SearchNew':
    key = inputSearchText()
    if key == None:
        pass
    else:
        key = repPolChars(key)
        addHistoryItem(my_addon_name, key)
        xbmc.executebuiltin('Container.Refresh')
        url = 'http://www.cda.pl/video/show/' + quote_plus(key) + '/p1?s=best'
        streamList(url, 'FilmList')
elif mode == 'SearchDel':
    deleteHistoryItem(my_addon_name, int(url))
    xbmc.executebuiltin('Container.Refresh')
elif mode == 'SearchMod':
    historyList = loadHistoryFile(my_addon_name)
    item = historyList[int(url)]
    key = inputSearchText(item)
    if key == '':
        deleteHistoryItem(my_addon_name, int(url))
    elif key == None:
        pass
    else:
        historyList[int(url)] = repPolChars(key)
        historyList = ';'.join(historyList)
        cache.set("history_" + my_addon_name, historyList)
    xbmc.executebuiltin('Container.Refresh')
elif mode == 'SearchRes':
    clearHistoryItems(my_addon_name)
elif mode == 'SearchFromList':
    searchFromList(url)
elif mode == 'Settings':
    my_addon.openSettings()
    xbmc.executebuiltin('Container.Refresh()')
elif mode == 'DecodeLink':
    decodeLink()
elif mode == 'addView':
    views.addView(args.get('content', [''])[0])
elif mode == 'SearchMeta':
    searchMeta(url, param0)
elif mode == 'SelectMeta':
    selectMeta()
elif mode == 'PremiumSort':
    premSort()
