# -*- coding: utf-8 -*-
import six,xbmc
from six.moves import urllib_request, urllib_parse

import json
import re

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'

def getUrl(url,data=None,cookies=None,ref=None):
	req = urllib_request.Request(url,data)
	req.add_header('User-Agent', UA)
	if cookies:
		req.add_header("Cookie", cookies)
	elif ref:
		req.add_header("Referer", ref)
	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 getContent(url='',category='latest_highlights',page='1',**kwargs):
	return parseContent(category,page)

def parseContent(category='10', page=1):

	url = 'https://api.meczyki.pl/api/shortcut/get-shortcuts?page={}&category={}'.format(page,category)
	
	content = getUrl(url)
	out=[]
	content = content.decode('utf-8') if six.PY2 else content
	data = json.loads(content)
	wc = data.get('shortcuts_list',[])
	
	for ij in wc:
	
		data = ij.get('date')
		for j in ij.get('shortcuts',[]):
			urln = j.get('url')
			urln = 'https://www.meczyki.pl'+urln if urln.startswith('/mecze/') else urln
			out.append(
				{'title': '[COLOR blue]%s [/COLOR]([B]%s[/B])'%(re.sub('(<.+?>)','',j.get('title','')), j.get('score','')),
				'url':urln,
				'code': '[COLOR khaki]%s[/COLOR], %s'%( j.get('competition_name'),data)
				})
	
	nextPage = {'category': category, 'page': int(page)+1 } if len(out) > 5 else False
	prevPage = {'category': category, 'page': int(page)-1 } if int(page) > 1 else False
	
	return out,(prevPage,nextPage)
def getStreamlet(url):
	html= getUrl(url).replace("\'",'"')
	src = re.compile('hls:"(//.*?)"').findall(html)[0]	
	src = 'http:'+src if src.startswith('//') else src
	return src
def getVideos(url):

	content = getUrl(url)
	v=[]
	content=content.replace("\'",'"')

	if 'ekstraklasa.tv/skro' in content:	
		iframe = re.compile('href="(http[s].*?ekstraklasa.tv.*?)"').findall(content)
	if 'ekstraklasa.org/aktual' in content:	
		iframe = re.compile('href="(.+://ekstraklasa.org.+?)"').findall(content)
	elif 'www.polsatsport.pl/film/' in content or 'www.polsatsport.pl/wiadomo' in content:
		iframe = re.compile('href="(.+polsatsport.pl\/.+?\/.+?)"').findall(content)		
	else:
		iframe = re.findall('<iframe.+?src="([^"]+)"',content,re.DOTALL+re.I)

	for (i,src) in enumerate(iframe):
		i=i+1
		v.append({'title':urllib_parse.urlparse(src).netloc+' - link %s'%i,'url':src})
	if not v:
		v={'msg':'Brak linku lub przekierowanie na inna strone.'}
	#
	return v

def getMain():
	content = getUrl('https://www.meczyki.pl/mecze')

	cat = re.findall('<div class="section-item"\s*data.+?><a href="([^"]+).+?><img src="([^"]+)"\s*data.+?>\s*(.+?)\s*<',content,re.DOTALL)
	out=[{'title':'Najnowsze Skróty','url':'','img':'meczykipl','params':{'category':0,'page':1}}]
	for category,img,title in cat:
		if 'http' in img:

			if title:
				img=(title.strip()).lower()
				if 'liga' in img:
					img='liga'
				elif 'dzynarodowe' in img:
					img ='fifa'
				elif 'inne' in img:
					img ='meczykipl'	
				category = re.findall('\w+\/(\d+)\/',category)[0]
				out.append({'title':title.strip(),'url':'','img':img,'params':{'category':category,'page':1}})
	return out

def getEkstrOrg(link):
	content = getUrl(link)
	src = re.compile('iframe.*src="(.+?)"').findall(content)#[0]	
	src = src[0] if src else ''
	
	if src:
		content = getUrl(src+'/config',ref=link)
		data = json.loads(content)	
		src = data['request']['files']['hls']['cdns']['fastly_skyfire']['url']

	return src
def getMatchat(link):
	content = getUrl(link)
	content=content.replace("\'",'"')
	m3u8=re.findall('hls\:|source\:"(.+?)"',content,re.DOTALL)[0]
	str='https:'+m3u8
	return str
	
def getUpclips(link):
	content = getUrl(link)
	content=content.replace("\'",'"')

	if 'Video Removed' in content:
		return ''
	try:
		m3u8=re.findall("""hlsSource\:|source\:['"](.+?)['"]""",content,re.DOTALL)[0]
	except:
		m3u8=re.findall("""src:\s*['"](.+?)['"].+?type:\s*['"]application""",content,re.DOTALL)#[0]#src: "
		if m3u8:
			m3u8=m3u8[0]
		else:
			m3u8=re.findall("""hls\:['"](.+?)['"]""",content,re.DOTALL)[0]

	if m3u8.startswith('//'): m3u8 = 'https:' + m3u8
	#str='https:'+m3u8
	return m3u8
	
def getAliezme(link):
	content = getUrl(link)
	content=content.replace("\'",'"').replace('&quot;','"')

	next_url = re.compile('src="(.+?)"\s*width\=').findall(content)

	url2 = next_url[0]
	url2 = 'https:'+url2 if url2.startswith('//') else url2
	content = getUrl(url2)
	content=content.replace("\'",'"')

	ff=re.findall('file:\s+"(.+?)"',content,re.DOTALL)
	str_url=''

	if ff:
		ff=ff[0]
		if ',' in ff:
			str_url = ff.split(',')[0]
		else:
			str_url = ff
	str_url = 'https:'+str_url if str_url.startswith('//') else str_url
	return	str_url 
