# -*- 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='http://estadios.pl/skroty-meczow'):
    content = getUrl(url)
    divs = re.compile('<div class="przyciski_lig">(.*?)</div>',re.DOTALL).findall(content)
    lgas = []
    if divs:
        lgas = re.compile('<a href="(.*?)".*title="(.*?)">').findall(divs[0])
    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(content):

    TRs = re.compile('<tr class="dol_ciemny_tr" itemscope itemtype="http://data-vocabulary.org/Event">(.*?)</tr>',re.DOTALL).findall(content)
    out=[]
    for tr in TRs:
        #title = re.compile('''<div itemprop="summary" style="font-size: 1px; color: .*?">(.*?)</div>(.*?)</td>''',re.DOTALL).findall(tr)
        
    #    teams = re.compile('''bold;">.+?urlklub">(.+?)</a>''',re.DOTALL).findall(tr)
        teams = re.compile('''class="urlklub">([^<]+)</a>''',re.DOTALL).findall(tr)
        
        
        href = re.compile('<a href="(.*?)" title="Zobacz mecz" itemprop="url">(.*?)</a>').findall(tr)
        imag=''

        dt = re.findall('time>(.+?)<',tr,re.DOTALL)
        dt = (dt[0].replace('\n','').replace('\t','')).strip()  if dt else ''

        if teams and href:
            title = ' vs '.join([team for team in teams])
            #tc = re.compile('>(.*?)<').search(title[0][1]).group(1) if '<' in title[0][1] else title[0][1].strip()

            u=href[0][0]
            c=href[0][1]
            t=(unicodePLchar('[COLOR blue]%s[/COLOR] [COLOR white][B](%s)[/B][/COLOR]'%(title,c))).replace("\n\t vs",'vs')            
            if 'strong' in c:
                pass
            else:
                out.append( {'title':t,'url':u,'code':'[COLOR white]'+dt+'[/COLOR]','img':imag} )

    np=re.findall('</font></a></span><span class="pkt"><a href="(.+?)">',content)#.findall(data)
    if np:
        np=np[0]
    return out,np

def getVideoLinks(url):
    content = getUrl(url)
    
    src=''
    iframe = re.compile('<div class="klip_film">(.*?)</div>',re.DOTALL).findall(content)
    if len(iframe)>1:
        #import urlparse
        import xbmcgui
        out=[]
        for (i,ifr) in enumerate(iframe):
            i=i+1
            if "a class='playable" in ifr:
                src = re.findall("""href=['"](.+?)['"]""",ifr)[0]
            else:
                src = re.findall("""src=['"](.*?)['"]""",ifr)[0]
            if src.startswith('//'): src = 'https:' + src
            host = urllib_parse.urlsplit(src).netloc
            host = '%s - link %s'%(host,i)
            out.append({'host':host,'href':src})
        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 iframe:
            if "a class='playable" in iframe[0]:
                src = re.findall("""href=['"](.+?)['"]""",iframe[0])#[0]
                src = src[0] if src else ''
            else:
                src = re.findall("""src=['"](.*?)['"]""",iframe[0])
                src = src[0] if src else ''
            if 'playwire' in src:
                src = re.findall('data-config="(.*?)"',iframe[0])
                src = src[0] if src else ''
            elif 'play.jpg' in src:
                src = re.findall("""href=['"](.*?)['"]""",iframe[0])[0]
    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
