# -*- coding: utf-8 -*-
import sys,re,os
import six
from six.moves import urllib_parse#, http_cookiejar
if six.PY3:
	unicode = str

#import urllib,urllib2
#import urlparse
import xbmc,xbmcgui,xbmcaddon, xbmcvfs
import xbmcplugin
import resolveurl as urlresolver
import time

import resources.lib.estadios as estadios
import resources.lib.ourmatch as ourmatch
import resources.lib.javafooty as javafooty
import requests
sess=requests.Session()

kukz=''
base_url		 = sys.argv[0]
addon_handle	 = int(sys.argv[1])
args			 = urllib_parse.parse_qs(sys.argv[2][1:])
my_addon		 = xbmcaddon.Addon()
addonName		= my_addon.getAddonInfo('name')
PATH			 = my_addon.getAddonInfo('path')

try:
	DATAPATH		= xbmcvfs.translatePath(my_addon.getAddonInfo('profile'))
except:
	DATAPATH		= xbmc.translatePath(my_addon.getAddonInfo('profile')).decode('utf-8')
	
RESOURCES		= PATH+'/resources/'
sys.path.append( os.path.join( RESOURCES, "lib" ) )
FANART		   = RESOURCES+'fanart.jpg'
FANART2= RESOURCES+'fanart2.jpg'
#ekstraklasa.GATE = ''
UA='Mozilla/5.0 (Linux; Android 7.0; PLUS Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36'

#if my_addon.getSetting('bramka') == 'true':
#	ekstraklasa.GATE = 'https://www.justproxy.co.uk/index.php?q='
	
def addLinkItem(name, url, mode, params=1, iconimage='DefaultFolder.png', infoLabels=False, IsPlayable=True, fanart=FANART,contextmenu=1):
	u = buildUrl({'mode': mode, 'foldername': name, 'ex_link' : url, 'params':params})
	liz = xbmcgui.ListItem(name)
	art_keys = ['thumb','poster','banner','fanart','clearart','clearlogo','landscape','icon']
	art = dict(zip(art_keys,[iconimage for x in art_keys]))
	art['landscape'] = fanart if fanart else art['landscape']
	art['fanart'] = fanart if fanart else art['landscape']
	liz.setArt(art)
	
	if not infoLabels:
		infoLabels={"title": name}
	
	liz.setInfo(type="video", infoLabels=infoLabels)
	
	if IsPlayable:
		liz.setProperty('IsPlayable', 'true')
	
	ok = xbmcplugin.addDirectoryItem(handle=addon_handle, url=u, listitem=liz,isFolder=False,totalItems=contextmenu)
	return ok

def addDir(name,ex_link=None, params=1, mode='folder',iconImage='DefaultFolder.png', infoLabels=None, fanart=FANART,contextmenu=None,page=1, mbebe=''):
	url = buildUrl({'mode': mode, 'foldername': name, 'ex_link' : ex_link, 'params' : params,'iconImage':iconImage,'mbebe':mbebe,'page':page})
	li = xbmcgui.ListItem(name)

	if infoLabels:
		li.setInfo(type="video", infoLabels=infoLabels)

	art_keys=['thumb','poster','banner','fanart','clearart','clearlogo','landscape','icon']
	art = dict(zip(art_keys,[iconImage for x in art_keys]))
	art['landscape'] = fanart if fanart else art['landscape']
	art['fanart'] = fanart if fanart else art['landscape']
	li.setArt(art)

	if contextmenu:
		info = contextmenu
		li.addContextMenuItems(info, replaceItems=True)
		
	xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,listitem=li, isFolder=True)

def encoded_dict(in_dict):
	try:
		# Python 2
		iter_dict = in_dict.iteritems()
	except AttributeError:
		# Python 3
		iter_dict = in_dict.items()
	out_dict = {}
	for k, v in iter_dict:
		if isinstance(v, unicode):
			v = v.encode('utf8')
		elif isinstance(v, str):
			v.decode('utf8')
		out_dict[k] = v
	return out_dict

def buildUrl(query):
	return base_url + '?' + urllib_parse.urlencode(encoded_dict(query))

def getLinks(ex_link):
	linksL = ekstraklasa.getVideoLinks(ex_link)
	stream_url = ''
	
	if len(linksL):
		if len(linksL) > 1:
			lables = [x.get('label') for x in linksL]
			s = xbmcgui.Dialog().select('Dostępne jakości',lables)
		else:
			s = 0
		stream_url=linksL[s].get('url') if s > -1 else ''
		host=linksL[s].get('label') if s > -1 else ''
	
	if stream_url:
		xbmcplugin.setResolvedUrl(addon_handle, True, xbmcgui.ListItem(path=stream_url))
	else:
		xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem(path=''))

def estadios_getLinks(ex_link):
	link = estadios.getVideoLinks(ex_link)
	stream_url = ''
	
	if link:
		if 'extragoals' in link:
			import resources.lib.extragoalsresolver as extragoalsresolver
			stream_url = extragoalsresolver.getVideoUrls(link)
		elif 'onet.tv' in link:
			from resources.lib.ekstraklasatv import getVideos as _getVideos
			src = _getVideos(link)
			if src:
				stream_url = src[0].get('url','')
		elif 'matchat.online' in link:
			import meczykipl
			stream_url=meczykipl.getMatchat(link)	
		elif 'streamable' in link:
			stream_url= estadios.getStreamable(link)
		elif 'upclips' in link or '.vidresults.com' in link:	  
			import meczykipl
			stream_url=meczykipl.getUpclips(link)	
		elif 'vidupstream.com' in link or 'forstreams.com' in link:	  
			import meczykipl
			stream_url=meczykipl.getUpclips(link)	
		elif 'vidstreamup' in link or 'tovidit.' in link:	  
			import meczykipl
			stream_url=meczykipl.getUpclips(link)	
		elif 'estreamall.com' in link or '.koravidstream.' in link:	  
			import meczykipl
			stream_url=meczykipl.getUpclips(link)   

		elif 'hofoot.'in link:   
			import meczykipl
			stream_url=meczykipl.getUpclips(link)  
		
		elif 'oms.' in link:
			import meczykipl
			stream_url=meczykipl.getStreamlet(link)	
		elif '/aliez.me/' in link:
			import meczykipl
			stream_url=meczykipl.getAliezme(link)  
		else:
			try:
				stream_url = urlresolver.resolve(link)
			except Exception as e:
				stream_url=''
				s = xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]',str(e))
	
	if stream_url:
		xbmcplugin.setResolvedUrl(addon_handle, True, xbmcgui.ListItem(path=stream_url))
	else:
		s = xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]','Link usunięty')
		xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem(path=''))

def import_mod(s):
	mod = {}
	if   s == 'laczynaspilka' : import laczynaspilka as mod
	elif s == 'ekstraklasatv' : import ekstraklasatv as mod
	elif s == 'meczykipl'	 : import meczykipl as mod
	return mod

mode = args.get('mode', None)
fname = args.get('foldername',[''])[0]
ex_link = args.get('ex_link',[''])[0]
rys = args.get('iconImage',[''])[0]
paramsy = args.get('params',[{}])[0]
page = args.get('page',[1])[0]
lnpurlmecze='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/subcompetition/filter?limit=9999&skip=0'
lnpurlpolec='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/video-library-group/list?ids=b5693a35-0617-4024-bea1-ccac3537754c&ids=ac4e9c00-6b95-4116-97c4-e2cafc8636e2&ids=ac79032f-502a-4d2f-8f64-357d4c9e3926&ids=20f8ace3-efed-4a96-9cb3-2e642ff0a770&ids=3e050267-f2d8-4f64-9b8d-188fe1e0affd&ids=5aa49267-e62f-4c6a-9238-953037467eb5&ids=a2ccbf43-7c8e-4bf4-93f9-453a706602e8'
lnpurl='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/video-library-group/list?ids=fe031114-b523-4f20-b641-bc4c3b31a532&ids=c20797e1-5ecc-47e2-b770-d57fa0bd657c&ids=ebff1f32-32c1-441d-a375-81e72df5115f&ids=062d1731-877b-4c55-add1-ce43760778bd&ids=e2ada13a-4910-4148-a33f-59ad96cf82d7&ids=b6833847-0e9c-47df-9a36-e14072a1c546&ids=3add93fe-bc8b-413d-bd29-758ebb44d7b0&ids=959c7253-63e0-4768-87dc-4f17b3e17a78&ids=67f3b3d3-d0fe-4beb-9ff2-c3e56597f73d&ids=59443106-7a52-4d23-b541-15fdb6f1afcf&ids=2ac09eb6-f0d8-4382-8025-e11881678d56&ids=b13e0f30-3006-4828-811d-fe007417b803&ids=8fc374da-83e0-4707-be11-9967d0865193&ids=c7f7a839-0ba0-4aac-a6d5-f658fe7ed8e2'


def router(paramstring):
	paramsx = dict(urllib_parse.parse_qsl(paramstring))
	if paramsx:
		mode = paramsx.get('mode', None)
		page = paramsx.get('page', None)
		if mode =='site':
			params = eval(paramsy)
			service = params.get('_service')
			act = params.get('_act')
			mod = import_mod(service)
		
			if act == 'main':
				items = mod.getMain()
				if len(items)>0:
					for one in items:
						if 'meczyki' in service or 'laczynaspilka' in service:
							fn=FANART2
							imagm=RESOURCES+one.get('img').replace('włochy','wlochy')+'.png'
						elif 'ekstraklasatv' in service:
							fn=FANART
							imagm=one.get('img')
							if not imagm:
								imagm=RESOURCES+'EkstraklasaTV.png' 
							#imagm=RESOURCES+'../icon.png'				
						else:
							fn=FANART
							imagm=one.get('img',RESOURCES+service+'.png')
						np = one.get('params',{})
						np['_service']=service
						np['_act']='content'
						addDir(one.get('title'), ex_link=one.get('url'), params=np, mode='site',iconImage=imagm,fanart=fn)
					xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
					xbmcplugin.endOfDirectory(addon_handle)
				
			elif act == 'content':

				params['_act']='play'
				if 'meczyki' in service or 'laczynaspilka' in service:
					fn=FANART2
				else:
					fn=FANART
				items,pagination = mod.getContent(ex_link,**params)
				if pagination[0]:
					pagination[0].update({'_service':service,'_act':'page'})
					addLinkItem(name='[COLOR blue]<< poprzednia strona <<[/COLOR]', url=pagination[0].get('urlp',''), params=pagination[0], mode='site', IsPlayable=False, iconimage=RESOURCES+'prevpage.png',fanart=fn)
				for one in items:
					if not one['url']:
						one['url']=''
					if 'powtcol' in one['url'] or one.get('mud'):
						np = one.get('params',{})
						np['_service']=service
						np['_act']='content'
						dalej = one.get('url')
						imagm=one.get('img')
						addDir(one.get('title'), ex_link=dalej, params=np, mode='site',iconImage=imagm,fanart=fn)
					else:
						addLinkItem(one.get('title',''), one['url'], params=params, mode='site', IsPlayable=True,infoLabels=one, iconimage=one.get('img'),fanart=fn)
				if pagination[1]:
					pagination[1].update({'_service':service,'_act':'page'})
					addLinkItem(name='[COLOR blue]>> następna strona >>[/COLOR]', url=pagination[1].get('urlp',''), params=pagination[1], mode='site', IsPlayable=False,iconimage=RESOURCES+'nextpage.png',fanart=fn)
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
				xbmcplugin.setContent(int(sys.argv[1]), 'files')		
				xbmcplugin.endOfDirectory(addon_handle)
			elif act == 'page':
				params['_act']='content'

				url = buildUrl({'mode': 'site', 'foldername': fname, 'ex_link' : ex_link,'params':params, })
				xbmc.executebuiltin('Container.Update(%s)'% url)
				xbmcplugin.endOfDirectory(addon_handle)
			elif act ==  'play' :
				if ex_link:
					streams = mod.getVideos(ex_link)
		
					resolved = False
					if isinstance(streams,list):
						if len(streams)>1:
							label = [x.get('title') for x in streams]
							s = xbmcgui.Dialog().select('Video',label)
							link = streams[s].get('url') if s>-1 else ''#quit()
							msg = streams[s].get('msg','')
							resolved = streams[s].get('resolved',False)
						else:
							try:
								link = streams[0].get('url',)
								msg = streams[0].get('msg','')
								resolved = streams[0].get('resolved',False)
							except:
								link = ''
								msg = 'Link not found at\n'+ex_link
					else:
						msg = streams.get('msg','')
						link = streams.get('url','')
					if link:
						
						if not resolved:
							try:
								
								import meczykipl
								if 'matchat.online' in link:
								
									stream_url=meczykipl.getMatchat(link)
									
								elif 'ekstraklasa.org' in link:	 
		
									stream_url=meczykipl.getEkstrOrg(link)
								elif 'ekstraklasa.tv' in link:					   
									import ekstraklasatv

									stream=ekstraklasatv.getVideos(link)
									stream_url=stream[0].get('url',)
								elif 'polsatsport.pl' in link:					   
									import polsatsport
									stream=polsatsport.getVideos(link)
									stream_url=stream.get('url',)
								elif 'videostreamlet' in link:	  
									
									stream_url=meczykipl.getStreamlet(link)	
								elif 'veuclips' in link:	  
									
									stream_url=meczykipl.getStreamlet(link)							
								elif 'viuclips' in link:	  
									
									stream_url=meczykipl.getStreamlet(link)	
									
								elif 'upclips' in link or '.vidresults.com' in link:  
								
									stream_url=meczykipl.getUpclips(link)	
								elif 'vidupstream.com' in link or 'forstreams.com' in link:	  
								
									stream_url=meczykipl.getUpclips(link)	
								elif 'vidstreamup' in link or 'tovidit.' in link:	
								
									stream_url=meczykipl.getUpclips(link)	
								elif 'llstreamup' in link:
									stream_url=meczykipl.getMatchat(link)					
								elif 'estreamall.com' in link or '.koravidstream.' in link:	  
									stream_url=meczykipl.getUpclips(link)  
								elif 'hofoot.'in link:	   
									stream_url=meczykipl.getUpclips(link)  
								elif '/meczpl.' in link:   
									stream_url=meczykipl.getUpclips(link)	
								elif '/aliez.me/' in link:
								  #  import meczykipl
									stream_url=meczykipl.getAliezme(link)  
								else:

									stream_url = urlresolver.resolve(link)

							except Exception as e:
								stream_url=''
								xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]',str(e))
						else:
							stream_url=link
						if stream_url: 
							play_item = xbmcgui.ListItem(path=stream_url)
							if '|DASH' in stream_url:

								licurl =''
								if 'licurl' in stream_url:
									stream_url,uap,typi,licurl = stream_url.split('|')
									licurl = licurl.split('curl=')[-1]
								else:
									stream_url,uap,typi = stream_url.split('|')
								stream_url = stream_url+'|'+uap
								play_item = xbmcgui.ListItem(path=stream_url)
								PROTOCOL = 'mpd'
								DRM = 'com.widevine.alpha'

								play_item.setMimeType('application/xml+dash')
								play_item.setContentLookup(False)
								import inputstreamhelper
								is_helper = inputstreamhelper.Helper('mpd', drm='com.widevine.alpha')
								if is_helper.check_inputstream():
									if sys.version_info >= (3,0,0):
										play_item.setProperty('inputstream', is_helper.inputstream_addon)
									else:
										play_item.setProperty('inputstreamaddon', is_helper.inputstream_addon)
								#if sys.version_info >= (3,0,0):
								#	play_item.setProperty('inputstream', 'inputstream.adaptive')
								#else:
								#	play_item.setProperty('inputstreamaddon', 'inputstream.adaptive')
								play_item.setProperty('inputstream.adaptive.manifest_type', PROTOCOL)  
								if licurl:
									hea = 'User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0&Content-Type='
									
									headers44 = {
										'Host': 'rbm-ekstraklasa.live.ott.irdeto.com',
										'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0',
										'accept': '*/*',
										'accept-language': 'pl,en-US;q=0.7,en;q=0.3',
										'referer': 'https://www.ekstraklasa.tv/',
										'origin': 'https://www.ekstraklasa.tv',
										'dnt': '1',
										'sec-fetch-dest': 'empty',
										'sec-fetch-mode': 'cors',
										'sec-fetch-site': 'cross-site',
										# Requests doesn't support trailers
										# 'te': 'trailers',
										'Content-Type': 'application/x-www-form-urlencoded',
									}
									hea= '&'.join(['%s=%s' % (name, urllib_parse.quote(value)) for (name, value) in headers44.items()]) 
									
									
									lic_url =  licurl+'|'+hea+'|R{SSM}|'	  
									play_item.setProperty('inputstream.adaptive.license_type', DRM)
									play_item.setProperty('inputstream.adaptive.manifest_update_parameter', 'full')
									play_item.setProperty('inputstream.adaptive.license_key', lic_url)
									play_item.setProperty('inputstream.adaptive.license_flags', "persistent_storage")

							xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item)
						else: 
							xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem(path=''))
					else:
						xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem(path=''))
				else:
					xbmcgui.Dialog().notification('[B]Błąd[/B]', 'Brak linku... ',xbmcgui.NOTIFICATION_INFO, 6000)

		elif mode.startswith('polsatsport'):
			import polsatsport as polsatsport
			if '_play_' in mode:
				stream_url = polsatsport.getVideos(ex_link)
				stream_url=stream_url.get('url',False)
				if stream_url: xbmcplugin.setResolvedUrl(addon_handle, True, xbmcgui.ListItem(path=stream_url))
				else: xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem(path=''))
			elif '_folder_' in mode:
				params = eval(paramsy)
				items = polsatsport.getContentDir(**params)
				for one in items:
					addDir(one.get('title'), ex_link=one.get('url'), params={}, mode='polsatsport_content_',iconImage=one.get('img'),fanart=FANART2)	
				xbmcplugin.endOfDirectory(addon_handle)
			elif '_content_' in mode:
				items,pagination = polsatsport.getContentVideos(ex_link)
				if pagination[0]: addLinkItem(name='[COLOR blue]<< poprzednia strona <<[/COLOR]', url='', params=pagination[0], mode='polsatsport_page_', IsPlayable=False,iconimage=RESOURCES+'prevpage.png',fanart=FANART2)	
				for one in items: addLinkItem(one.get('title',''),  one['url'], mode='polsatsport_play_', IsPlayable=True,infoLabels=one, iconimage=one.get('img'),fanart=FANART2)	
				if pagination[1]: #addDir('[COLOR blue]>> następna strona >>[/COLOR]', ex_link='', params={'type':'dyscypliny'}, mode='polsatsport_page_',iconImage=RESOURCES+'polsatsport.png',fanart=FANART2)

				
				
					addLinkItem(name='[COLOR blue]>> następna strona >>[/COLOR]', url='', params=pagination[1], mode='polsatsport_page_', IsPlayable=False,iconimage=RESOURCES+'nextpage.png',fanart=FANART2)	
				xbmcplugin.endOfDirectory(addon_handle)
			elif '_page_' in mode:
				url = buildUrl({'mode': 'polsatsport_content_', 'foldername': '', 'ex_link' : paramsy,'params':'', })
				xbmc.executebuiltin('Container.Update(%s)'% url)
				xbmcplugin.endOfDirectory(addon_handle)		
			else:
				addDir('Magazyny', ex_link='', params={'type':'magazyny'}, mode='polsatsport_folder_',iconImage=RESOURCES+'polsatsport.png',fanart=FANART2)
				addDir('Dyscypliny', ex_link='', params={'type':'dyscypliny'}, mode='polsatsport_folder_',iconImage=RESOURCES+'polsatsport.png',fanart=FANART2)
				xbmcplugin.endOfDirectory(addon_handle)
		elif mode.startswith('lechtv'):
			import resources.lib.lechtv as lechtv
		
			if '_tabela_' in mode:
		
				items = lechtv.tabela_ekstraklasy()
				for one in items: addLinkItem(one.get('title',''),  '', mode='', infoLabels=one,IsPlayable=False,iconimage=RESOURCES+'ekstraklasa.png',fanart=FANART)
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
				xbmcplugin.setContent(int(sys.argv[1]), 'files')
			elif '_strzelcy_' in mode:
				items = lechtv.strzelcy()
				for one in items: 
					addLinkItem(one.get('title',''),  '', mode='', infoLabels=one,IsPlayable=False,iconimage=RESOURCES+'ekstraklasa.png',fanart=FANART)
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")	
				xbmcplugin.setContent(int(sys.argv[1]), 'files')	
			elif '_terminarz_' in mode:		
				items = lechtv.terminarz()
				for one in items: 
					addDir(one.get('title'), ex_link=one.get('url'), params={}, mode='lechtv_content_',iconImage=RESOURCES+'ekstraklasa.png',fanart=FANART)
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
			elif '_page_' in mode:
				url = buildUrl({'mode': 'lechtv_content_', 'foldername': '', 'ex_link' : '','params':paramsy, })
				xbmc.executebuiltin('Container.Refresh(%s)'% url)
						
			elif '_content_' in mode:
				items = lechtv.getContent(ex_link)
				for one in items:
					addLinkItem(one.get('title',''),  '', mode='', IsPlayable=False,infoLabels=one, iconimage=RESOURCES+'ekstraklasa.png')
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
				xbmcplugin.setContent(int(sys.argv[1]), 'files')
			xbmcplugin.endOfDirectory(addon_handle)			
		
		elif mode =='meczreplay_main':	
			import lechtv
			url = lechtv.getUrlReplay()
			addDir('[COLOR yellow]Strona główna[/COLOR]',ex_link=url,params={}, mode='meczreplay',iconImage=RESOURCES+'meczreplay.png',fanart=FANART2)
		#	addDir('[COLOR yellow]Szukaj[/COLOR]',ex_link='http://meczreplay.blogspot.com/search?q=',params={}, mode='meczreplay_search',iconImage=RESOURCES+'search.png',fanart=FANART2)
	   #	 addDir('   Ekstraklasa',ex_link='http://meczreplay.blogspot.com/search/label/ekstraklasa',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)	
	   #	 addDir('   Ekstraklasa po godzinach',ex_link='http://meczreplay.blogspot.com/search/label/ekstraklasa%20po%20godzinach',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Cafe Futbol',ex_link='http://meczreplay.blogspot.com/search/label/Cafe%20Futbol',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Liga Mistrzów',ex_link='http://meczreplay.blogspot.com/search/label/liga%20mistrz%C3%B3w',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Liga Europy',ex_link='http://meczreplay.blogspot.com/search/label/liga%20europy',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Liga Narodów',ex_link='http://meczreplay.blogspot.com/search/label/liga%20narod%C3%B3w',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Mundial 2018',ex_link='http://meczreplay.blogspot.com/search/label/mundial%202018',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Mecz',ex_link='http://meczreplay.blogspot.com/search/label/mecz',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Bundesliga',ex_link='http://meczreplay.blogspot.com/search/label/bundesliga',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Ligue 1',ex_link='http://meczreplay.blogspot.com/search/label/ligue1',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Premier League',ex_link='http://meczreplay.blogspot.com/search/label/premier%20league',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Serie A',ex_link='http://meczreplay.blogspot.com/search/label/seriea',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   F1',ex_link='http://meczreplay.blogspot.com/search/label/F1',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Eleven F1',ex_link='http://meczreplay.blogspot.com/search/label/Eleven%20F1',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)
	   #	 addDir('   Boks',ex_link='http://meczreplay.blogspot.com/search/label/boks',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)	
	   #	 addDir('   MMA',ex_link='http://meczreplay.blogspot.com/search/label/mma',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)		
	   #	 addDir('   UFC',ex_link='http://meczreplay.blogspot.com/search/label/ufc',params={}, mode='meczreplay',iconImage=RESOURCES+'empty.png',fanart=FANART2)	
			xbmcplugin.endOfDirectory(addon_handle)		
			
		elif mode =='meczreplay_search':		
			query = xbmcgui.Dialog().input(u'Search... ', type=xbmcgui.INPUT_ALPHANUM,)
			if query:	  
				query=query.replace('+','%2B').replace(' ','+')
				import resources.lib.lechtv as lechtv
				itemz,np=lechtv.mecz_replay(ex_link+query)
				if itemz:
					for f in itemz:
						addDir(f.get('title'),f.get('url'), params={}, mode='meczreplay_getLinks',iconImage=f.get('img'),fanart=FANART2)			
					if np:
						np=np.replace('&amp;','&')
						addDir('[COLOR blue]>> następna strona >>[/COLOR]',ex_link=np,params={}, mode='meczreplay',iconImage=RESOURCES+'nextpage.png',fanart=FANART2)	
					xbmcplugin.endOfDirectory(addon_handle)	
					
				else:
					xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]','Brak wyników')
					quit()
		
		elif mode =='meczreplay':
			import resources.lib.lechtv as lechtv
			itemz,np=lechtv.mecz_replay(ex_link)
			for f in itemz:
				#addDir(f.get('title'),f.get('url'), params={}, mode='meczreplay_getLinks',iconImage=f.get('img'),fanart=FANART2)	
				addLinkItem(name=f.get('title'), url=f.get('url'), mode='meczreplay_play', iconimage=f.get('img'), infoLabels=f, IsPlayable=True,fanart=FANART2)	
			if np:
				np=np.replace('&amp;','&')
				addDir('[COLOR blue]>> następna strona >>[/COLOR]',ex_link=np,params={}, mode='meczreplay',iconImage=RESOURCES+'nextpage.png',fanart=FANART2)	
			xbmcplugin.endOfDirectory(addon_handle)	
		
		elif mode =='meczreplay_getLinks':
			import resources.lib.lechtv as lechtv
			itemz=lechtv.mecz_replay_getLinks(ex_link,fname,rys)
			
			for one in itemz:	
				tyt=one.get('title','')
				imag=one.get('img','')
				href=one.get('url','')		
				addLinkItem(name=tyt, url=href, mode='meczreplay_play', iconimage=imag, infoLabels=one, IsPlayable=True,fanart=FANART2)	
			xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%P, %G")	
			xbmcplugin.setContent(int(sys.argv[1]), 'files')	
			xbmcplugin.endOfDirectory(addon_handle)
		
		elif mode =='meczreplay_play':	

			if 'zippyshare' in ex_link:
				import resources.lib.lechtv as lechtv
				stream_url=lechtv.mecz_replay_getZippy(ex_link)	
			elif 'send.cm' in ex_link:
				import resources.lib.lechtv as lechtv
				stream_url=lechtv.getnewStream(ex_link)
			else:
				try:
					stream_url = urlresolver.resolve(ex_link)
					if not stream_url:
						import resources.lib.lechtv as lechtv
						stream_url = lechtv.getnewStream(ex_link)	
				except Exception as e:
					stream_url=''
					xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]',str(e))
			
			if stream_url:
				xbmcplugin.setResolvedUrl(addon_handle, True, xbmcgui.ListItem(path=stream_url))
			else:
				xbmcgui.Dialog().notification('[B]Błąd[/B]', 'Brak resolvera',xbmcgui.NOTIFICATION_INFO, 6000)
				quit()
			
		elif mode =='skroty':	
			addDir('[COLOR yellow]Estadios.pl[/COLOR]',ex_link='http://estadios.pl/skroty-meczow',params={}, mode='Estadios_skroty_Liga',iconImage=RESOURCES+'estadios.png',fanart=FANART2)
			addDir('[COLOR yellow]Meczyki.pl[/COLOR]',ex_link='',params={'_service':'meczykipl','_act':'main'}, mode='site',iconImage=RESOURCES+'meczykipl.png',fanart=FANART2)
			addDir('[COLOR yellow]OurMatch[/COLOR]',ex_link='',params={}, mode='our_match_main',iconImage=RESOURCES+'ourmatch.png',fanart=FANART2)		
			addDir('[COLOR yellow]Javafooty[/COLOR]',ex_link='https://www.javafooty.com/',params={}, mode='foothighlights',iconImage=RESOURCES+'javafooty.png',fanart=FANART2)	
			xbmcplugin.endOfDirectory(addon_handle)
			
		elif mode =='foothighlights':
		
			addDir('[COLOR orange][B]Search (club/team)[/COLOR][/B]','https://www.javafooty.com/', params={}, mode='javafooty_searchhigh',iconImage=RESOURCES+'search.png',fanart=FANART2)
			addDir('Europe','https://www.javafooty.com/', params={}, mode='javafooty_getcomp',iconImage=RESOURCES+'uefa.png',fanart=FANART2)	
			addDir('South America','https://www.javafooty.com/', params={}, mode='javafooty_getcomp',iconImage=RESOURCES+'conmebol.png',fanart=FANART2)	
			addDir('North & Central America','https://www.javafooty.com/', params={}, mode='javafooty_getcomp',iconImage=RESOURCES+'concacaf.png',fanart=FANART2)	
			addDir('Asia','https://www.javafooty.com/', params={}, mode='javafooty_getcomp',iconImage=RESOURCES+'afc.png',fanart=FANART2)	
			addDir('Africa','https://www.javafooty.com/', params={}, mode='javafooty_getcomp',iconImage=RESOURCES+'caf.png',fanart=FANART2)	
			addDir('Oceania','https://www.javafooty.com/', params={}, mode='javafooty_getcomp',iconImage=RESOURCES+'ofc.png',fanart=FANART2)	
			addDir('World','https://www.javafooty.com/', params={}, mode='javafooty_getcomp',iconImage=RESOURCES+'fifa.png',fanart=FANART2)	
			xbmcplugin.endOfDirectory(addon_handle)	
		
		elif mode =='javafooty_getcomp':	
		
			links = javafooty.getCompetition(fname)
			for f in links:
				ikonka = 'https://raw.githubusercontent.com/Proximus2000/mb-support/master/flags/%s.png'%(urllib_parse.quote(f.get('title').lower()))
				addDir(f.get('title'),f.get('href'), params={}, mode='sportpieces',iconImage=ikonka,fanart=FANART2)	
			xbmcplugin.endOfDirectory(addon_handle)	
			
		elif mode =='sportpieces':	
			page = int(page) if page else 1	
			links,pagination = javafooty.getSportpieces(ex_link,page)
			if links:
				for f in links:
					addDir(f.get('title'),f.get('href'), mode='javafooty_getLinks2',iconImage=rys,fanart=FANART2)	
				if pagination[1]:	
					addDir('[COLOR blue]>> next page >>[/COLOR]',ex_link, params={}, mode='sportpieces',iconImage=RESOURCES+'nextpage.png',fanart=FANART2,page=pagination[1])	
				xbmcplugin.endOfDirectory(addon_handle)
			else:
				xbmcgui.Dialog().notification('Info,', 'Brak materiałów do wyświetlenia', RESOURCES+'javafooty.png', 6000)
		
			
		elif mode =='javafooty_searchhigh':	
			query = xbmcgui.Dialog().input(u'Search... ', type=xbmcgui.INPUT_ALPHANUM,)
			if query:	  
				out=javafooty.ListsearchhighNew(query)
				for one in out:	
					tyt=one.get('title','')
					imag=one.get('img','')
					href=one.get('href','')	
					addDir(one.get('title'),one.get('href'), mode='javafooty_getLinks2',iconImage=one.get('img',''),fanart=FANART2,infoLabels=one)
					#addLinkItem(name=tyt, url=href, mode='javafooty_getLinks', iconimage=imag, infoLabels=one, IsPlayable=True,fanart=FANART2)
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%P, %G")
				xbmcplugin.setContent(addon_handle, 'videos')	
				xbmcplugin.endOfDirectory(addon_handle)
		
		elif mode =='javafooty_searchdate':	
			query = xbmcgui.Dialog().input(u'Enter date', type=xbmcgui.INPUT_DATE)	
			if query:			
				out=javafooty.Listdate(ex_link,query)
				for one in out:	
					tyt=one.get('title','')
					imag=one.get('img','')
					href=one.get('url','')	
					addLinkItem(name=tyt, url=href, mode='javafooty_getLinks', iconimage=imag, infoLabels=one, IsPlayable=True,fanart=FANART2)
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%P, %G")
				xbmcplugin.setContent(addon_handle, 'videos')	
				xbmcplugin.endOfDirectory(addon_handle)		
		
			
		elif mode == 'javafooty_getLinks2':		
			out,outw=javafooty.getLinks(ex_link,fname)
			if out:	
				for one in out:	
					tyt=one.get('title','')
					href=one.get('url','')	
					addLinkItem(name=tyt, url=href, mode='javafooty_getLinks', iconimage=rys, infoLabels=one, IsPlayable=True,fanart=FANART2)
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%P, %G")
				xbmcplugin.setContent(addon_handle, 'videos')	
				xbmcplugin.endOfDirectory(addon_handle)	
		elif mode == 'javafooty_getLinks':
			linkstr = ex_link
			linkstr = 'http:'+linkstr if linkstr.startswith('//') else linkstr
			if linkstr and not'about:' in linkstr:
				nextlink=javafooty.getUrlReq(linkstr)  
				if six.PY3:
					nextlink = nextlink.decode(encoding='utf-8', errors='strict')
				vido_url=''
				empla=re.findall('emb\..+?\.me/',linkstr)
		
				if empla:
					vido_url=re.findall("file:.+?'(htt.+?),",nextlink)[0]
				elif 'mycujoo' in linkstr:
					vido_url=re.findall('"file".+?"(ht.+?m3u.+?)"',nextlink)[0]
					vido_url=vido_url.split('master')[0]+'480p/playlist.m3u8'
					vido_url+='|User-Agent='+UA+'&Referer='+linkstr
				elif 'matchat' in linkstr:
					vido_url=javafooty.getMatchat(linkstr)
				elif 'videostreamlet.net' in linkstr or 'clipsrom' in linkstr:
					vido_url=javafooty.getStreamlet(linkstr)
				elif 'veuclips' in linkstr:
					vido_url=javafooty.getStreamlet(linkstr)			
				elif 'streamable' in linkstr:
					try:
						vido_url=re.findall('"url": *"(.+?)"',nextlink)[0].replace('&amp;','&')
					except:
						vido_url=''
					if vido_url.startswith('//'):
						vido_url='https:'+vido_url
				elif 'streamja.com' in linkstr:
					vido_url=javafooty.getStreamja(linkstr)
			
				elif 'upclips' in linkstr or '.vidresults.com' in linkstr:	 
					import meczykipl
					vido_url=meczykipl.getUpclips(linkstr)
					
				elif 'vidupstream.com' in linkstr or 'forstreams.com' in linkstr:	  
					import meczykipl
					vido_url=meczykipl.getUpclips(linkstr)	
				elif 'vidstreamup' in linkstr or 'tovidit.' in linkstr:	  
					import meczykipl
					vido_url=meczykipl.getUpclips(linkstr)	
				elif 'estreamall.com' in linkstr or 'videohat.' in linkstr:	  
					import meczykipl
					vido_url=meczykipl.getUpclips(linkstr)	
				elif '.koravidstream.' in linkstr or 'hofoot.'in linkstr:	
					import meczykipl
					vido_url=meczykipl.getUpclips(linkstr)			
				elif '/meczpl.' in linkstr:   
					import meczykipl
					vido_url=meczykipl.getUpclips(linkstr)
				elif 'oms.' in linkstr: 
					import meczykipl
		
					vido_url=meczykipl.getStreamlet(linkstr)	
				elif '/aliez.me/' in linkstr: 
					import meczykipl
					vido_url=meczykipl.getAliezme(linkstr) 
				else:
					try:
						vido_url = urlresolver.resolve(linkstr)
					except Exception as e:
						xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]',str(e))
				if vido_url:
			
					li = xbmcgui.ListItem(offscreen=True)
					li.setPath(vido_url)
			
					xbmcplugin.setResolvedUrl(addon_handle, True, li)
			
				else:
					xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]',"Can't resolve or no links")
					xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem(path=''))	
			else:
				xbmcgui.Dialog().notification('[B][COLOR red]Problem[/COLOR][/B]', "Can't resolve or no link",RESOURCES+'javafooty.png', 6000)
				
		elif mode =='Estadios_skroty':

			out,np=estadios.get_skroty_meczow(ex_link,page)
			for f in out:
				addLinkItem(name=f.get('title'), url=f.get('url'), mode='Estadios_play', iconimage=f.get('img'), infoLabels=f, IsPlayable=True,fanart=FANART2)	
			if np:
				addDir('[COLOR blue]>> następna strona >>[/COLOR]',ex_link=ex_link,params={}, mode='Estadios_skroty',iconImage=RESOURCES+'nextpage.png',fanart=FANART2, page = np)	
			xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
			xbmcplugin.setContent(int(sys.argv[1]), 'files')		
			xbmcplugin.endOfDirectory(addon_handle)
			
		elif mode =='Estadios_skroty_Liga':
			#addDir('Szukanie','search', params={}, mode='Estadios_search',iconImage=RESOURCES+'search.png',fanart=FANART2)
			data = estadios.get_liga()

			if data:
				for x in data:

					imag = x.get('img', None).lower()
					t = x.get('title', None)
					hr = x.get('url', None)
					addDir(t,ex_link=hr,params={}, mode='Estadios_skroty',iconImage=RESOURCES+imag+'.png',fanart=FANART2)
			xbmcplugin.endOfDirectory(addon_handle)
		
		elif mode =='Estadios_search':		
		
			query = xbmcgui.Dialog().input(u'Szukaj drużyny:', type=xbmcgui.INPUT_ALPHANUM,)
			if query:	  
				itemz=estadios.get_search(query)
				if itemz:
					for f in itemz:
						imag=f.get('img')
						if not imag:
							imag=RESOURCES+'empty.png'
						addDir(f.get('title'),f.get('url'), params={}, mode='Estadios_search_matches',iconImage=imag,fanart=FANART2)	
					xbmcplugin.endOfDirectory(addon_handle)	
				else:
					xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]','Brak wyników')
					quit()	
		elif mode =='Estadios_search_matches':	
			mainesturl='https://estadios.pl/'
			kukz = args.get('mbebe',[{}])[0]
			if kukz:
				cookies={'PHPSESSID': kukz}
				html=sess.get(ex_link,cookies=cookies)
			else:
				cookies=''
				html=sess.get(ex_link)
				kukz= html.cookies['PHPSESSID']
			out,np=estadios.get_skroty_meczow(html.content)
			if out:
				for f in out:
					addLinkItem(name=f.get('title'), url=f.get('url'), mode='Estadios_play', iconimage=f.get('img'), infoLabels=f, IsPlayable=True,fanart=FANART2)	
				if np:
					addDir('[COLOR blue]>> następna strona >>[/COLOR]',ex_link=mainesturl+np,params={}, mode='Estadios_skroty',iconImage=RESOURCES+'nextpage.png',fanart=FANART2)	
				xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
				xbmcplugin.setContent(int(sys.argv[1]), 'files')		
				xbmcplugin.endOfDirectory(addon_handle)		
			else:
				quit()
		
		elif mode =='our_match_main':
			if not ex_link:
				addDir('Search...','search', params={}, mode='our_match_getMatches',iconImage=RESOURCES+'search.png',fanart=FANART2)
				addDir('Most Recent','http://ourmatch.net/', params={}, mode='our_match_getMatches',iconImage=RESOURCES+'new.png',fanart=FANART2)		
				out = ourmatch.main()
				for one in out:	
					tyt=one.get('title','')
					imag=one.get('img','')
					href=one.get('url','')		
					addDir(tyt, href, params={}, mode='our_match_main',iconImage=RESOURCES+imag,fanart=FANART2)
			else:
				ikon=rys
				out = ourmatch.main(name=ex_link)
				for one in out:	
					tyt=one.get('title','')
					imag=one.get('img','')
					href=one.get('url','')	
					addDir(tyt, href, params={}, mode='our_match_getMatches',iconImage=ikon,fanart=FANART2)				
			xbmcplugin.endOfDirectory(addon_handle)	
			
		elif mode =='our_match_getMatches':	
			ilo = args.get('mbebe',[{}])[0]
			out,np = ourmatch.getMatches(ex_link,ilo)
			for one in out:	
				tyt=one.get('title','')
				imag=one.get('img','')
				href=one.get('url','')		
				addDir(tyt, href, params={}, mode='our_match_getStreams',iconImage=imag,fanart=FANART2)	
			if np:
				if 'loadmor' in np:
					npx,curp,maxp,posts = np.split('|')#'loadmore|{}|{}|{}'.format(str(curp),str(maxp),str(posts))
				addDir('[COLOR blue]>> next page >>[/COLOR]', np, params={}, mode='our_match_getMatches',iconImage=RESOURCES+'nextpage.png',fanart=FANART2,mbebe=maxp)
			xbmcplugin.endOfDirectory(addon_handle)	
			
		elif mode =='our_match_getStreams':
		
			out = ourmatch.getStreams(fname,ex_link,rys)
			for one in out:	
				tyt=one.get('title','')
				imag=one.get('img','')
				href=one.get('url','')		
				addLinkItem(name=tyt, url=href, mode='our_match_play', iconimage=imag, infoLabels=one, IsPlayable=True,fanart=FANART2)
			xbmcplugin.endOfDirectory(addon_handle)	
			
		elif mode =='our_match_play':
			stream_url=ourmatch.play(fname,ex_link)
			if stream_url:
				xbmcplugin.setResolvedUrl(addon_handle, True, xbmcgui.ListItem(path=stream_url))
			else:
				quit()
		
		elif mode =='Estadios_play':
			estadios_getLinks(ex_link)
		
		elif mode == 'Opcje':
			my_addon.openSettings()
		
		elif mode =='getLinks':
			getLinks(ex_link)
		
		elif mode =='getVideos':
			params = eval(params)
			Litems,pagination = ekstraklasa.getVideos(**params)
			if pagination[0]:
				addLinkItem(name='[COLOR blue]<< poprzednia strona <<[/COLOR]', url=ex_link, mode='__page__', params=pagination[0], IsPlayable=False)
			items=len(Litems)
			for f in Litems:
				f['code']= f.get('duration_formatted','')
				f['code']='[COLOR lightgreen]onAir[/COLOR]' if f.get('onair',False) else f['code']
				addLinkItem(name=f.get('title'), url=f.get('id'), mode='getLinks', iconimage=f.get('thumbnail_240_url'), infoLabels=f, IsPlayable=True,contextmenu=items,fanart=f.get('img'))
			
			if pagination[1]:
				addLinkItem(name='[COLOR blue]>> następna strona >>[/COLOR]', url=ex_link, mode='__page__', params=pagination[1], IsPlayable=False)
			xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
			xbmcplugin.setContent(int(sys.argv[1]), 'files')
			xbmcplugin.endOfDirectory(addon_handle)
			
		elif mode == '__page__':
			url = buildUrl({'mode': 'getVideos', 'foldername': '', 'ex_link' : ex_link, 'params': params})
			xbmc.executebuiltin('Container.Refresh(%s)'% url)
			xbmcplugin.endOfDirectory(addon_handle)
		elif mode == 'Opcje':
			my_addon.openSettings()
		
		elif mode == 'folder':
			pass
		
		elif mode =='wybor':	
			import tabele	
			dane = tabele.getWybor(ex_link)
			stream_url=''
			t = [ x.get('title') for x in dane]
			u = [ x.get('url') for x in dane]
			sel = xbmcgui.Dialog().select('Co pokazać?', t)
			if sel>-1:
					nxturl = dane[sel].get('url')
					if 'terminarz' in nxturl:
						import tabele
						out= tabele.getTerminarz(nxturl)
						for one in out:	
							tyt=one.get('title','')
							imag=one.get('img','')
							href=one.get('url','')		
							addDir(tyt, href, params={}, mode='termincd',iconImage=rys,fanart=FANART2)
						xbmcplugin.endOfDirectory(addon_handle)			
					elif '/grupy/' in nxturl or '/tabela/' in nxturl:
						import tabele
						nxturl=nxturl.split('|')
						if 'no' in nxturl[1]:
							out= tabele.getTabelaGrupy(nxturl[0])
							for one in out:	
								tyt=one.get('title','')
								imag=one.get('img','')
								href=one.get('url','')		
								addDir(tyt, href, params={}, mode='grupycd',iconImage=rys,fanart=FANART2)
							xbmcplugin.endOfDirectory(addon_handle)	
						else:
							import tabele
							out= tabele.getTabelaKraj(nxturl[0])
							for one in out:	
								tyt=one.get('title','')
								imag=one.get('img','')
								href=one.get('url','')		
								addLinkItem(name=tyt, url=href, mode=' ', iconimage=rys, infoLabels=one, IsPlayable=False,fanart=FANART2)
							xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
							xbmcplugin.setContent(int(sys.argv[1]), 'videos')
							xbmcplugin.endOfDirectory(addon_handle)		
					elif 'strzelcy' in	nxturl:
						import tabele
						out= tabele.getStrzelcy(nxturl)
						for one in out:	
							tyt=one.get('title','')
							imag=one.get('img','')
							href=one.get('url','')		
							addLinkItem(name=tyt, url=href, mode=' ', iconimage=rys, infoLabels=one, IsPlayable=False,fanart=FANART2)
						xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
						xbmcplugin.setContent(int(sys.argv[1]), 'videos')
						xbmcplugin.endOfDirectory(addon_handle)					
						
		elif mode =='listtabterm':	
			import tabele
			out= tabele.getListTerminarz()
			for one in out:	
				tyt=one.get('title','')
				imag=one.get('img','')
				href=one.get('url','')	
				href=href.split('|')	
				addDir(tyt, href[0], params={}, mode='wybor',iconImage=RESOURCES+imag,fanart=FANART2)	
			xbmcplugin.endOfDirectory(addon_handle)
		
		elif mode =='grupycd':	
			druz = eval(urllib_parse.unquote(ex_link))
			for one in druz:	
				tyt=one.get('title','')
				imag=one.get('img','')
				href=one.get('url','')	
				if fname in href:
					addLinkItem(name=tyt, url=href, mode=' ', iconimage=rys, infoLabels=one, IsPlayable=False,fanart=FANART2)
				else:
					continue
			xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
			xbmcplugin.setContent(int(sys.argv[1]), 'videos')
			xbmcplugin.endOfDirectory(addon_handle)	
		
		elif mode =='ytarchive':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UC_DZQrnboIncQCBB7QdMKOg/)')
		elif mode =='ytarchive2':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/user/EkstraklasaORG/)')
		elif mode =='ytarchive3':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCFlGSuyqfui9DwttuET8MzQ/)')
		elif mode =='ytarchive4':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCcz1Tizq8IFdEguy3smvnhA/)')
		elif mode =='ytarchive5':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCIfI7Yo22SMKp5PraztHM6w/)')
		elif mode =='ytarchive6':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCQcQIQHhoOX0SxLMe2eOO3A/)')
		elif mode =='ytarchive7':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCWqWpkCENcewhasG98SGflg/)')
		elif mode =='ytarchive8':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCSAMYthmI9mzM92Z8HVw4dQ/)')
		elif mode =='ytarchive9':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCLfyph6Lt4hj8ER-0uPBS5g/)')
		elif mode =='ytarchive10':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCHRDYVS8yGBJHLVOAW93Y_g/)')
		elif mode =='ytarchive11':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/user/PiknikTV/)')
		elif mode =='ytarchive12':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCEY2HOFOu6suqwPTdEgcc8g/)')
		elif mode =='ytarchive13':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCsYwdezrMNOzPQgI8k84ZlQ/)')
		elif mode =='ytarchive14':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/channel/UCzrrRDXtuMoB9ae-WKamQIQ/)')
		elif mode =='ytarchive15':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/user/PrzegladSportowy/)')
		elif mode =='ytarchive16':
			xbmc.executebuiltin('container.Update(plugin://plugin.video.youtube/user/SportplWideo/)')
			
		elif mode =='ytkan':
			addLinkItem('[COLOR yellow]Ekstraklasa[/COLOR]','','ytarchive2',IsPlayable=False,iconimage=RESOURCES+'ekstrklasa.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Łączy nas piłka[/COLOR]','','ytarchive3',IsPlayable=False,iconimage=RESOURCES+'laczynaspilka.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Łączy nas piłka TV[/COLOR]','','ytarchive4',IsPlayable=False,iconimage=RESOURCES+'laczynaspilkatv.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Kanał Sportowy[/COLOR]','','ytarchive5',IsPlayable=False,iconimage=RESOURCES+'kanalsportowy.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Weszło TV[/COLOR]','','ytarchive6',IsPlayable=False,iconimage=RESOURCES+'WeszloTV.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Prawda Futbolu[/COLOR]','','ytarchive7',IsPlayable=False,iconimage=RESOURCES+'prawdafutbolu.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Polsport - Michał Pol[/COLOR]','','ytarchive8',IsPlayable=False,iconimage=RESOURCES+'Polsport.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Foot Truck[/COLOR]','','ytarchive9',IsPlayable=False,iconimage=RESOURCES+'foottruck.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Foot Truck Live[/COLOR]','','ytarchive10',IsPlayable=False,iconimage=RESOURCES+'foottrucklive.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Piknik TV[/COLOR]','','ytarchive11',IsPlayable=False,iconimage=RESOURCES+'pikniktv.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Po Gwizdku[/COLOR]','','ytarchive12',IsPlayable=False,iconimage=RESOURCES+'pogwizdku.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Etoto TV[/COLOR]','','ytarchive13',IsPlayable=False,iconimage=RESOURCES+'etototv.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]newonce.sport[/COLOR]','','ytarchive14',IsPlayable=False,iconimage=RESOURCES+'newoncesport.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Przeglad Sportowy[/COLOR]','','ytarchive15',IsPlayable=False,iconimage=RESOURCES+'przegladsportowy.png',fanart=FANART2)
			addLinkItem('[COLOR yellow]Sport.pl[/COLOR]','','ytarchive16',IsPlayable=False,iconimage=RESOURCES+'sportpl.png',fanart=FANART2)
			xbmcplugin.endOfDirectory(addon_handle)	
			
		elif mode =='ektv':
			addDir('[COLOR blue]Ekstraklasa.tv[/COLOR]',ex_link='',params={'_service':'ekstraklasatv','_act':'main'}, mode='site',iconImage=RESOURCES+'EkstraklasaTV.png')
			addLinkItem('[COLOR blue]Ekstraklasa Archives[/COLOR]','','ytarchive',IsPlayable=False,iconimage=RESOURCES+'EkstraklasaTV.png',)
			xbmcplugin.endOfDirectory(addon_handle)	
		
		elif mode =='laczynaspilkamenu':
		
			addDir('[COLOR blue]Mecze[/COLOR]',ex_link=lnpurlmecze,params={}, mode='laczynaspilkamenu2',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Polecane multimedia[/COLOR]',ex_link=lnpurlpolec,params={}, mode='laczynaspilka',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Wideoteka[/COLOR]',ex_link=lnpurl,params={}, mode='laczynaspilka',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			
			xbmcplugin.endOfDirectory(addon_handle)
			
		elif mode =='laczynaspilkamenu2':
		
			mainurl='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/subcompetition/filter?competitionId={}&limit=9999&skip=0'
		
			addDir('[COLOR blue]Mistrzostwa Świata[/COLOR]',ex_link=mainurl.format('47ca772c-afc0-4dd8-97d6-27d76b92d791'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Mistrzostwa Europy[/COLOR]',ex_link=mainurl.format('93ade638-f0c4-4598-9fb9-6e9d84ef68e5'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Igrzyska Olimpijskie[/COLOR]',ex_link=mainurl.format('b9387ec2-3ab8-46d9-82c4-b50b07fce7a4'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Liga Narodów[/COLOR]',ex_link=mainurl.format('6a31ffd7-64be-4977-9dae-3ed29c82284d'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Mecze Towarzyskie[/COLOR]',ex_link=mainurl.format('0b5443d8-cda1-4dc0-af5b-53b56ddfc020'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Mecze nieoficjalne[/COLOR]',ex_link=mainurl.format('2cc0b375-a5d4-4df7-86ed-8485fb905cf1'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Młodzieżowe mistrzostwa świata[/COLOR]',ex_link=mainurl.format('0858f428-2e4f-4b3c-bf95-940f76000bef'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Młodzieżowe mistrzostwa Europy[/COLOR]',ex_link=mainurl.format('e5f08ce4-aa41-49bc-9326-c18108286ebb'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Młodzieżowe mecze towarzyskie[/COLOR]',ex_link=mainurl.format('ab3e3048-2975-48db-a3f7-cb55b2607032'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Mistrzostwa świata kobiet[/COLOR]',ex_link=mainurl.format('eb86a03a-2f41-4f14-8c52-64517b285e73'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Mistrzostwa Europy kobiet[/COLOR]',ex_link=mainurl.format('3c7cacfd-be59-4892-9638-df2814917e7c'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Mecze towarzyskie kobiet[/COLOR]',ex_link=mainurl.format('b045e300-90f4-4362-b5c6-e336f67987f8'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			
			addDir('[COLOR blue]Puchar Polski[/COLOR]',ex_link=mainurl.format('0394fbf5-c030-4043-b5b5-14d4f7c4dae1'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
			addDir('[COLOR blue]Europejskie puchary[/COLOR]',ex_link=mainurl.format('e79bce6c-be6f-444f-a8e9-10038e72a9b3'),params={}, mode='lnpcateg',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
		
			
			
			
			
			xbmcplugin.endOfDirectory(addon_handle)
		
		elif mode =='laczynaspilka':
			import laczynaspilka as lnp
			usrlnp = my_addon.getSetting('usernamelnp')
			pwdlnp = my_addon.getSetting('passwordlnp')
			a=True
			try:
				if usrlnp and pwdlnp:# my_addon.getSetting('usernamelnp') and my_addon.getSetting('passwordlnp')
					a = lnp.loguj(usrlnp, pwdlnp)
			except:
				pass
			if a:
				out = lnp.GetCategory(ex_link)
				for one in out:	
					tyt=one.get('title','')
					imag=one.get('img','')
					imag = imag if imag else RESOURCES+'laczynaspilka.png'
					href=(one.get('url','')	).split('|')[0]
					addDir(tyt, href, params={}, mode='lnpcateg',iconImage=imag,fanart=FANART2)		
				xbmcplugin.endOfDirectory(addon_handle)	
			else:
				addLinkItem('[COLOR gold]Zaloguj[/COLOR]','','zalogujlnp',IsPlayable=False,fanart=FANART2,iconimage=RESOURCES+'ustaw.png',)
		
				xbmcplugin.endOfDirectory(addon_handle)	
			
		elif mode =='lnpcateg':
		  #  xbmc.log('@#@part0: %s' , xbmc.LOGNOTICE)
			import laczynaspilka as lnp
			out = lnp.getSubCateg(ex_link,fname)
			for one in out:	
				tyt=one.get('title','')
				imag=one.get('img','')
				imag = imag if imag else RESOURCES+'laczynaspilka.png'
			#	href=one.get('url','')	
				href=(one.get('url','')	).split('|')[0]
				#xbmc.log('@#@hrefhrefhref: %s'%((one.get('url','')	)) , xbmc.LOGNOTICE)
				try:
					cos = (one.get('url','')	).split('|')[1]
				except:
					cos='nic'
				md = 'lnpcateg3' if cos == 'mat' else 'lnpcateg2'	
				addDir(tyt, href, params={}, mode=md,iconImage=imag,fanart=FANART2)		
			xbmcplugin.endOfDirectory(addon_handle)	
		
		elif mode =='lnpcateg2':
	   #	 xbmc.log('@#@part1: %s' , xbmc.LOGNOTICE)
			import laczynaspilka as lnp
			out = lnp.getSubCateg(ex_link,fname)
			for one in out:	
				tyt=one.get('title','')
				imag=one.get('img','')
				imag = imag if imag else RESOURCES+'laczynaspilka.png'
				href=(one.get('url','')	).split('|')[0]
				addDir(tyt, href, params={}, mode='lnpcateg3',iconImage=imag,fanart=FANART2)		
			xbmcplugin.endOfDirectory(addon_handle)	
		
		
			
		elif mode =='lnpcateg2x':
		#	xbmc.log('@#@part2: %s' , xbmc.LOGNOTICE)
			import laczynaspilka as lnp
			out = lnp.GetCategory(ex_link)
			for one in out:	
				tyt=one.get('title','')
				imag=one.get('img','')
				imag = imag if imag else RESOURCES+'laczynaspilka.png'
				href=(one.get('url','')	).split('|')[0]
				addDir(tyt, href, params={}, mode='lnpcateg3',iconImage=imag,fanart=FANART2)		
			xbmcplugin.endOfDirectory(addon_handle)	
		
		elif mode =='lnpcateg3':
		#	xbmc.log('@#@part3: %s' , xbmc.LOGNOTICE)
			import laczynaspilka as lnp
			out = lnp.getMaterial(ex_link,fname)
			for one in out:	
				tyt=one.get('title','')
				imag=one.get('img','')
				
				href=one.get('url','')	
				opis = one.get('code','')	
				opis = opis if opis else tyt
				addLinkItem(name=tyt, url=href, mode='playlnp', iconimage=imag, infoLabels={'title': tyt,'plot':opis}, IsPlayable=True,fanart=FANART2)		
			xbmcplugin.endOfDirectory(addon_handle)	
		elif mode =='playlnp':
			import laczynaspilka as lnp
			link = lnp.getLink(ex_link)
		
			xbmcplugin.setResolvedUrl(addon_handle, True, xbmcgui.ListItem(path=link))
			
			
			
		#getMaterial(url)
			
		elif mode =='termincd':	
			import tabele
			aa=re.findall('\[B\](.+?)\[\/CO',fname,re.DOTALL)[0]
			out= tabele.getTerminarzCD(ex_link,aa)
			for one in out:	
				tyt=one.get('title','')
				imag=one.get('img','')
				href=one.get('url','')	
				addLinkItem(name=tyt, url=href, mode=' ', iconimage=rys, infoLabels=one, IsPlayable=False,fanart=FANART2)
			xbmcplugin.addSortMethod(addon_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE, label2Mask = "%R, %Y, %P")
			xbmcplugin.setContent(int(sys.argv[1]), 'videos')
			xbmcplugin.endOfDirectory(addon_handle)	
			
		elif mode == 'zalogujlnp':
			my_addon.openSettings()
			#xbmc.executebuiltin('Container.Refresh(%s)'% url)
			xbmc.executebuiltin('Container.Refresh')
		
		
		
		
		
		
	else:
	  #  home()
	  #  xbmcplugin.endOfDirectory(addon_handle)	



#if mode is None:
		addDir('[COLOR blue]Ekstraklasa.tv[/COLOR]',ex_link='',params={}, mode='ektv',iconImage=RESOURCES+'EkstraklasaTV.png',fanart=FANART2)
		addDir('[COLOR blue]Polsat Sport[/COLOR]',ex_link='',params={}, mode='polsatsport',iconImage=RESOURCES+'polsatsport.png',fanart=FANART2)	
		addDir('[COLOR blue]Łączy nas piłka[/COLOR]',ex_link=lnpurl,params={}, mode='laczynaspilkamenu',iconImage=RESOURCES+'laczynaspilka.png',fanart=FANART2)	
		addDir('[COLOR blue]Kanały YT[/COLOR]',ex_link='',params={}, mode='ytkan',iconImage=RESOURCES+'KanalyYT.png',fanart=FANART2)
		addDir('[COLOR blue]Mecz Replay[/COLOR]',ex_link='http://meczreplay.blogspot.com/search',params={}, mode='meczreplay_main',iconImage=RESOURCES+'meczreplay.png',fanart=FANART2)	
		addDir('[COLOR yellow]Skróty meczów[/COLOR]',ex_link='',params={}, mode='skroty',iconImage=RESOURCES+'skroty.png',fanart=FANART2)
		addDir('[COLOR yellow]Tabele, terminarze, strzelcy[/COLOR]',ex_link='',params={}, mode='listtabterm',iconImage=RESOURCES+'tabela.png',fanart=FANART2)	
		addLinkItem('[COLOR gold]Opcje[/COLOR]','','Opcje',IsPlayable=False,fanart=FANART2,iconimage=RESOURCES+'ustaw.png',)
		xbmcplugin.endOfDirectory(addon_handle)
	

#else:
	
#	xbmcplugin.setResolvedUrl(addon_handle, False, xbmcgui.ListItem(path=None))
	
	
if __name__ == '__main__':
	router(sys.argv[2][1:])	