# -*- coding: utf-8 -*-
import re,os
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


import json

#from urlparse import urlparse
import base64
#import cookielib
#from CommonFunctions import parseDOM
import requests
sess=requests.Session()

BASEURL= "http://estadios.pl"
TIMEOUT = 10
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'
kuk=''
def getUrl(url,data=None,cookies=None):
	req = urllib_request.Request(url,data)
	req.add_header('User-Agent', UA)
	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 get_liga(url='https://estadios24.pl/_next/data/XOClD9cIPli55tfMS9y4J/skroty-meczow.json'):

	url='https://estadios24.pl/'
	content = getUrl(url)

	build = re.findall('"buildId"\:\s*"(.+?)"',content,re.DOTALL)[0]
	main_url= 'https://estadios24.pl/_next/data/'+build
	aa=main_url+'/index.json'

	content = getUrl(aa)

	content = json.loads(content)

	pages = content.get('pageProps', None).get('promoted_cats', None)
	lgas=[]

	for x in pages:
		title = x.get('name', None)
		id_ = x.get('id', None)

		href = main_url + '/'+x.get('plain', None)+'-skroty-meczow.json'
		imag = x.get('name_old', None)

		lgas.append( {'title':title,'url':href+'|'+str(id_),'img':imag})

	return lgas
	
def get_search(query):
	data = {'druzyna_szukaj': query,}
	
	headers = {
		'User-Agent': UA,
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
		'Accept-Language': 'pl,en-US;q=0.7,en;q=0.3',
		'Content-Type': 'application/x-www-form-urlencoded',
		'Connection': 'keep-alive',
		'Upgrade-Insecure-Requests': '1',
		'TE': 'Trailers',}
	out=[]
	html = sess.post('https://estadios.pl/index.php?s=szukaj', headers=headers, data=data).content
	if six.PY3:
		html= html.encode(encoding='utf-8', errors='strict')
	result = parseDOM(html,'div', attrs={'class': "lewa_strona"})[0]
	items = parseDOM(result,'p')
	for item in items:
		href = parseDOM(item,'a',ret='href')[0]
		imag=get_imag(href)
		title = parseDOM(item,'a')[0]
		out.append( {'title':title,'url':href,'img':imag})
	return out
def get_imag(url):
	html=getUrl(url)
	try:
		result = parseDOM(html,'span', attrs={'itemprop': "address"})[0]
		imag = parseDOM(result,'img',ret='src')[0]
		imag = 'https://estadios.pl/'+imag if imag.startswith('dodane') else imag
	except:
		imag=''
	return imag
def get_skroty_meczow(url,pagex):

	page = int(pagex)-1
	href, id_	=	url.split('|')
	build = re.findall('data\/(.+?)\/',href,re.DOTALL)[0]

	mainurl = 'https://estadios24.pl/_next/data/'+build+'/'

	out = []
	json_data = {
		'sort': 'latest',
		'page': int(page),
		'type': 'cat',
		'id': int(id_),
	}
	hdrs = {
		'Host': 'api.estadios24.pl',
		'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0',
		'accept': 'application/json, text/plain, */*',
		'accept-language': 'pl,en-US;q=0.7,en;q=0.3',
		'origin': 'https://estadios24.pl',
	}
	xx=''

	response = sess.post('https://api.estadios24.pl/api/highlight/type', headers=hdrs, json=json_data)#.text
	for x in response.json():

		idx = str(x.get("id", None))
		event = x.get("event", None)
		team1_score = str(event.get("team1_score", None))
		team2_score = str(event.get("team2_score", None))
		team1 = event.get("team1", None).get("name", None)
		team2 = event.get("team2", None).get("name", None)
		
		plain = event.get("plain", None)

		ab = team1 +' - '+team2
		ab2 = team1_score+':'+team2_score
		tt='[COLOR blue]%s [/COLOR]([B]%s[/B])'%(ab,ab2)
		
		from datetime import datetime

		timestamp = event.get("datestamp", None)
		local_dt = datetime.fromtimestamp(timestamp)
		czas=local_dt.strftime('%Y-%m-%d %H:%M')
		data = local_dt.strftime('%d-%m-%Y')
		nturl = mainurl +plain+'-skrot-meczu-'+data+'.json'

		out.append( {'title':tt,'url':nturl,'code':'[COLOR white]'+czas+'[/COLOR]','img':'none'} )

	np = int(pagex)+1 if out else 0
	return out,np

def getVideoLinks(url):
	vids = json.loads(getUrl(url))

	src=''
	vids = vids.get('pageProps', None).get('data', None).get('videos', None)

	if len(vids)>1:
		import xbmcgui
		out=[]
		for i,vid in enumerate(vids, start=1):
			embed = vid.get('embed', None)
			href = re.findall("href\s*=\s*'(.+?)'",embed,re.DOTALL)[0]

			host = urllib_parse.urlsplit(href).netloc
			host = '%s - link %s'%(host,i)
			out.append({'host':host,'href':href})
		hosts = [x.get('host') for x in out]
	
		sel = xbmcgui.Dialog().select('Wybierz ',hosts)
		
		sel = sel if sel>-1 else quit()
		src=out[sel].get('href')
		
	else:
		if vids:
			embed = vids[0].get('embed', None)
			src = re.findall("href\s*=\s*'(.+?)'",embed,re.DOTALL)

	return src
def getStreamable(url):
	content = getUrl(url)
	try:
		src=re.findall('href="(.+?token.+?)"',content)[0].replace('&amp;','&')
	except:
		src=''
	if src.startswith('//'):
		src='https:'+src
	return  src
def test():
	out = get_skroty_meczow(url)
	for one in out:
		getVideoLinks(one.get('url'))

def unicodePLchar(txt):
   # s='JiNcZCs7'
   # if six.PY3:
  #	  s= s.encode(encoding='utf-8', errors='strict')
   #@ txt = re.sub(base64.b64decode(s),'',txt)
	txt = re.sub('&quot;','"',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
