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

import six, xbmc
from six.moves import urllib_request, urllib_parse
if six.PY3:
	LOGNOTICE = xbmc.LOGINFO
	from resources.lib.cmf3 import parseDOM
else:
	LOGNOTICE = xbmc.LOGNOTICE
	from resources.lib.cmf2 import parseDOM
from resources.lib import dehunt as dhtr
import json
import re,os, requests
import xbmcaddon
my_addon		 = xbmcaddon.Addon()

BASEURLTAB = 'https://sportowefakty.wp.pl/pilka-nozna/ekstraklasa/tabele'
urlstrz="https://ekstraklasa.tv/tabela?tid=v7gpy"
TIMEOUT = 10
UA	  = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
UAx = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0'
iteppp  = 25

sess=requests.Session()

def getUrl(url,data=None,cookies=None):
	req = urllib_request.Request(url,data)
	req.add_header('User-Agent', UA)

	if cookies:
		req.add_header("Cookie", cookies)
	try:
		response = urllib_request.urlopen(req,timeout=TIMEOUT)
		link = response.read()
		response.close()
	except:
		link=''
	if six.PY3:
		link= link.decode(encoding='utf-8', errors='strict')
	return link
def getUrlReplay():
	headers = {
		'Host': 't.me',
		'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0',
		'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
		'accept-language': 'pl,en-US;q=0.7,en;q=0.3',
		'dnt': '1',
		'upgrade-insecure-requests': '1',
		'sec-fetch-dest': 'document',
		'sec-fetch-mode': 'navigate',
		'sec-fetch-site': 'none',
		'sec-fetch-user': '?1',
		# Requests doesn't support trailers
		# 'te': 'trailers',
	}
	
	response = sess.get('https://t.me/s/zobaczto', headers=headers)#.text
	abc = response.cookies
	my_cookies = requests.utils.dict_from_cookiejar(abc)
	found = ['%s=%s' % (name, value) for (name, value) in my_cookies.items()]
	kukz= ';'.join(found)
	my_addon.setSetting('tmekuks',kukz)
	nturl = re.findall('canonical"\s*href="([^"]+)"',response.text,re.DOTALL)[0]
	cooks = dict(urllib_parse.parse_qsl(kukz))
	href = 'https://t.me/s/zobaczto'+nturl
	return href
	
def mecz_replay(url):
	kukz = my_addon.getSetting('tmekuks')
	
	cooks = dict(urllib_parse.parse_qsl(kukz))
	#if not '?q=' in url:
	nturl = re.findall('(\d+)',url,re.DOTALL)[-1] if not '?q=' in url else 0
	np=False
	
	if int(nturl) != 0 and int(nturl)>20:
	
		zam = int(nturl)-20
	
		np =  re.sub(str(nturl), str(zam), url)
	
	hdrs = {
		'Host': 't.me',
	
		'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0',
		'accept': 'application/json, text/javascript, */*; q=0.01',
		'accept-language': 'pl,en-US;q=0.7,en;q=0.3',
		'x-requested-with': 'XMLHttpRequest',
		'origin': 'https://t.me',
		'dnt': '1',
		'referer': 'https://t.me/s/zobaczto',
		'sec-fetch-dest': 'empty',
		'sec-fetch-mode': 'cors',
		'sec-fetch-site': 'same-origin',
	
		'Content-Type': 'application/x-www-form-urlencoded',
	}
	
	response = sess.post(url, cookies=cooks, headers=hdrs).json()
	bubbles = parseDOM(response,'div', attrs={'class': "tgme_widget_message_bubble"})[::-1]
	out=[]
	for bubble in bubbles:
		srcs=[]
		try:
			bubble = bubble.replace('<mark class="highlight">','').replace('</mark>','')
			
			title = re.findall('text"\s*dir\s*=\s*"auto">([^<]+)',bubble,re.DOTALL)

			if not title:
				title = re.findall('title\s*"\s*dir\s*=\s*"auto">([^<]+)',bubble,re.DOTALL)
			if title:
				title = title[0]
			else:
				continue
			imag = re.findall("image:url\(\\'(.*?)'",bubble,re.DOTALL)[0]
			bubble = re.sub('(<i.*?<\/i>)','',bubble)
			href = re.findall('noopener">([^<]+)',bubble,re.DOTALL)#[0]
			if len(href )>1:

				t1href = re.findall('>([^<]+)<br\/><a href="([^"]+)',bubble,re.DOTALL)
				t1href = t1href if len(t1href)>0 else  re.findall('<br\/>(.*?)<br\/><a href="([^"]+)',bubble,re.DOTALL)
				for x,y in t1href:
					x = x if x else title
					if '<br/>' in x:
						x = re.findall('<br\/>([^<]+)',x,re.DOTALL)[0]
					srcs.append( {'title':x,'url':y} )	
			else:
				href = href[0]
			out.append( {'title':title,'url':href,'img':imag,'srcs':urllib_parse.quote_plus(str(srcs))} )
		except:

			pass
	return out,np

	
def getnewStream(url):
	hd = {'User-Agent': UAx}
	src = ''
	import ssl
	try:
		_create_unverified_https_context = ssl._create_unverified_context
	except AttributeError:
		pass
	else:
		ssl._create_default_https_context = _create_unverified_https_context
	
	
	if 'tubeload.co' in url:
		hd = {
			'Host': 'tubeload.co',
			'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0',
			'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
			'accept-language': 'pl,en-US;q=0.7,en;q=0.3',
			'dnt': '1',
			'sec-fetch-dest': 'document',
			'sec-fetch-mode': 'navigate',
			'sec-fetch-site': 'none',
			'sec-fetch-user': '?1',
			'te': 'trailers',}
	
	
	html = sess.get( url, headers = hd, timeout =30, verify=False).text 
	
	zz=''

	if 'streamlare.' in url:
		id = re.findall('\/v\/(.+?)$',url)[0]
		hdrs = {
			'User-Agent': UAx,
			'Accept': 'application/json, text/plain, */*',
			'Accept-Language': 'pl,en-US;q=0.7,en;q=0.3',
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/json;charset=utf-8',
			'Origin': 'https://streamlare.com',
			'Connection': 'keep-alive',
			'Referer': url,
			'Sec-Fetch-Dest': 'empty',
			'Sec-Fetch-Mode': 'cors',
			'Sec-Fetch-Site': 'same-origin',
			'Cache-Control': 'max-age=0',
			'TE': 'trailers',
		}
		
		data = {'id':id}
	
		response = sess.post('https://streamlare.com/api/video/get', headers=hdrs, cookies=sess.cookies, json=data).json()
	
		src = response.get("result",None).get('Original',None).get('src',None)
		
		
		import base64
		orig = base64.b64decode(src)
		try:
			xrange
		except Exception:
			xrange = range  
			
		if six.PY3:
			orig = orig.decode(encoding='utf-8', errors='strict')
		def decode_char(index):
			old_charcode = ord(orig[index])
			new_charcode = 0x33 ^ old_charcode
			try:
				new_char = chr(new_charcode)
			except:
				new_char = new_charcode
			return new_char
			
		video_url =''
		for i in xrange(len(orig)):
			video_url+=decode_char(i)
		src = video_url
		
	elif 'send.cm' in url:
		srcx=re.findall('source src="([^"]+)"',html,re.DOTALL)
		src = srcx[0] if srcx else src

	elif 'tubeload.co' in url:
	
		ffk=re.findall('function\(h,u,n,t,e,r\).*?}.*?}\((".+?)\)\)',html,re.DOTALL)
		dd =""
	
	
	
		for ff in ffk:
	
			ff=ff.replace('"','')
			h, u, n, t, e, r = ff.split(',')
			
			cc = dhtr.dehunt (h, int(u), n, int(t), int(e), int(r))
			cc = cc.replace('\\"','"').replace("\'",'"')
			dd+=cc
	
	
		ffcfdfccfdcf=re.findall('var ffcfdfccfdcf="([^"]+)"',dd,re.DOTALL)
		
		
		
		dbdfeecacaec=re.findall('var dbdfeecacaec="([^"]+)"',dd,re.DOTALL)
		if dbdfeecacaec:

			import base64
			res = dbdfeecacaec[0].replace("ZTcxNWM1NzQ0ZjgyMmFiNTgwMTQyYWU5MmFiYzRlNzU", "");
			res2 = res.replace("ZjI3YTQ3MzQ4N2IwZGI1ZDU1YzFjMjkyZGQ3ZTc4ZGE=", "")
			src = base64.b64decode(res2)
			if six.PY3:
				src = src.decode(encoding='utf-8', errors='strict')
	
		else:
			ddx = re.findall('(.+?)typeplayer',dd,re.DOTALL)[0]
			dds = re.findall('"([^"]+)',ddx,re.DOTALL)#[0]
			for d in dds:
				if 'aHR0' in d:
	
					srcd = re.findall('(aHR0.+?)$',d,re.DOTALL)[0]
					try:
						import base64
	
						src = base64.b64decode(srcd)
						if six.PY3:
							src = src.decode(encoding='utf-8', errors='strict')
						if '.mp4' in src:
							src = re.findall('(.+?\.mp4)',src,re.DOTALL)[0]
							
							break
					except:
						pass
	if src:
		src+='|User-Agent='+urllib_parse.quote(UAx)+'&auth=SSL/TLS&verifypeer=false'
	
	return src	
def createStreamsb(url):
	import random
	url = url[:-1] if url[-1] == '/' else url
		
	if ".html" in url : url_id= url.split("/")[-1].split(".")[-2]
	else: url_id = url.split("/")[-1]

	def rand_str():
		array = "abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
		return "".join([random.choice(array) for _ in range(12)])
			
	def hex_encode(string: str):
		return (string).encode("utf-8").hex()

	part_one = f"{rand_str()}||{url_id}||{rand_str()}||streamsb"
	final_url = f"https://sbanh.com/sources16/{hex_encode(part_one)}"
	headers={"watchsb":"sbstream", "referer":"url", "user-agent":"Mozilla/5.0 (Linux; Android 11; 2201116PI) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Mobile Safari/537.36"}
	response = requests.get(final_url, headers=headers).json()
	vid_url = ''
	x = response.get('stream_data', None)
	if x:
		vid_url = x.get('file', None)+'|'+urllib_parse.urlencode(headers)
	return vid_url
	
def mecz_replay_getLinks(url,plot,rys):
	out=[]	
	import ast
	srcs = ast.literal_eval(urllib_parse.unquote_plus(url))
	for x in srcs:
		
		out.append( {'title':x.get('title'),'url':x.get('url'),'img':rys,'plot':plot} )

	return out
	
def get_d(html):
	d=re.findall('<span id="omg" class="(\d+)" style="display',html)[0]
	return int(d)* 2
	
def a(): 
	return 1
def b(): 

	return a() + 1
def c(): 

	return b() + 1
	
def mecz_replay_getZippy(url):
	html = getUrl(url).replace("\'",'"')
	cz1=urllib_parse.urlsplit(url).netloc
	czesc=re.findall('''\(['"]dlbutton['"]\).href = ['"](.+?)['"]\+(\(.+?\))\+['"](.+?)['"]''',html)[0]
	d=get_d(html)
	obl=int(eval(czesc[1]))
	video_url='https://'+cz1+czesc[0]+str(obl)+czesc[2]	+'|Referer='+url
	return video_url
	
def tabela_ekstraklasy():
	content= getUrl(BASEURLTAB)
	tabela = re.compile('<tr class="podium-first">(.*?)</tbody>',re.DOTALL).findall(content)
	out = []

	if tabela:	
		pos = re.compile('<td class="align--left"><span>(.*?)</span></td>').findall(tabela[0])
		pts = re.compile('<td class="align--left"><b>(.*?)</b></td>').findall(tabela[0])
		team = re.compile('<td class="align--left"><a href=".*?">(.*?)</a></td>').findall(tabela[0])
		for p,pt,name in zip(pos,pts,team):
			out.append({'title':'%s. [B]%s[/B]'%(p,name),'code':'[COLOR gold][B]%s[/B][/COLOR]'%unicodePLchar(pt)} )

	return out
def strzelcy():
	content= getUrl(urlstrz)
	out = []
	result=parseDOM(content,'div', attrs={'class': "tableWrapper "})[0]	 
	links = parseDOM(result, 'tr', attrs={'id': "row\d+"}) 
	for link in links:  
		bb=parseDOM(link,'span', attrs={'class': "itemName"}) #[0]
		poz=bb[0]
		nazw=bb[1]
		klub=bb[2]
		br=bb[4]	
		out.append({'title':poz+'. [B]'+nazw+' [COLOR lightblue]('+klub+')[/COLOR][/B]','code':'[COLOR gold][B]'+br+'[/B][/COLOR]'} )
	return out
def terminarz():
	out=[	
		{'url':"http://ekstraklasa.tv/tabela?tid=j4np6",'title':"1. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=2bz1f",'title':"2. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=ewjd3",'title':"3. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=zvwe0",'title':"4. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=d9en7",'title':"5. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=3m886",'title':"6. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=bf397",'title':"7. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=lbz65",'title':"8. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=xr9xp",'title':"9. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=z14k4",'title':"10. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=edksn",'title':"11. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=npe4e",'title':"12. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=9qge0",'title':"13. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=py5dm",'title':"14. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=pdzls",'title':"15. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=9g3bm",'title':"16. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=4p9pk",'title':"17. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=57whe",'title':"18. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=st9rr",'title':"19. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=s3p3n",'title':"20. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=zexf1",'title':"21. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=6pzy8",'title':"22. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=t096j",'title':"23. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=y1lc1",'title':"24. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=8fjrk",'title':"25. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=yp628",'title':"26. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=xcrv7",'title':"27. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=hy3ff",'title':"28. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=mpjzs",'title':"29. kolejka"},
		{'url':"http://ekstraklasa.tv/tabela?tid=be7lk",'title':"30. kolejka"},]
	return out
def getContent(url):
	content= getUrl(url)
	result=parseDOM(content,'table', attrs={'class': "otable collapse  tableDetai.*?"})[0]  
	links = parseDOM(result, 'tr', attrs={'id': "row\d+"}) 
	out=[]
	for link in links:
		gosp=parseDOM(link,'td', attrs={'class': "teamAndScorers crest"})[0]
		gosp=parseDOM(gosp,'span', attrs={'class': "itemName"})[0]
		gosc=parseDOM(link,'td', attrs={'class': "teamAndScorers crest"})[1]
		gosc=parseDOM(gosc,'span', attrs={'class': "itemName"})[0]
		try:
			wynik=parseDOM(link,'td', attrs={'class': " score "})[0]
			wc=parseDOM(wynik,'span', attrs={'class': "itemName"}) #[0]
			a=wc[1]
		except:
			date=parseDOM(link,'td', attrs={'class': "excludeExtra matchDate "})[0]  
			wc=parseDOM(date,'span', attrs={'class': "itemName"}) #[0]
		out.append({'title':gosp+' - '+gosc,'code':'[COLOR gold][B]'+wc[0]+' [/B][/COLOR]'+wc[1]} )
	return out
def unicodePLchar(txt):
	s='JiNcZCs7'
	txt = re.sub(s.decode('base64'),'',txt)
	txt = re.sub('&nbsp;','',txt)
	txt = re.sub('&.*;','',txt)
	txt = txt.replace('&nbsp;','')
	txt = txt.replace('&lt;br/&gt;',' ')
	txt = txt.replace('&ndash;','-')
	txt = txt.replace('&quot;','"').replace('&amp;quot;','"')
	txt = txt.replace('&oacute;','ó').replace('&Oacute;','Ó')
	txt = txt.replace('&amp;oacute;','ó').replace('&amp;Oacute;','Ó')
	txt = txt.replace('&amp;','&')
	txt = txt.replace('\u0105','ą').replace('\u0104','Ą')
	txt = txt.replace('\u0107','ć').replace('\u0106','Ć')
	txt = txt.replace('\u0119','ę').replace('\u0118','Ę')
	txt = txt.replace('\u0142','ł').replace('\u0141','Ł')
	txt = txt.replace('\u0144','ń').replace('\u0144','Ń')
	txt = txt.replace('\u00f3','ó').replace('\u00d3','Ó')
	txt = txt.replace('\u015b','ś').replace('\u015a','Ś')
	txt = txt.replace('\u017a','ź').replace('\u0179','Ź')
	txt = txt.replace('\u017c','ż').replace('\u017b','Ż')

	return txt
