# -*- coding: utf-8 -*-
import six, xbmc   
from six.moves import urllib_request, urllib_parse    
if six.PY3:    
    LOGNOTICE = xbmc.LOGINFO    
 
else:    
    LOGNOTICE = xbmc.LOGNOTICE    


import re,os

import base64

BASEURL = "www.polsatsport.pl"
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):
    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 getContentDir(type='magazyny'):
    if type=='magazyny':
        return getMagazyny()
    elif type == 'dyscypliny':
        return getDyscypliny()
    return []

def getDyscypliny():
    url='http://www.polsatsport.pl/wideo-lista/'
    url = 'https://www.polsatsport.pl/wideo/'
    content = getUrl(url)
    out=[]

    content = re.findall('container__nav nav--section overflow-menu(.*?)<\/nav>',content)[0]
    
    
    
    
    ids = [(a.start(), a.end()) for a in re.finditer('<li class="nav__item', content)]
    ids.append( (-1,-1) )
    out=[]
    mTittle = ['[COLOR blue][B]%s[/B][/COLOR]','[COLOR green][B]%s[/B][/COLOR]']
    sTittle = ['   [COLOR lightblue]%s[/COLOR]','   [COLOR lightgreen]%s[/COLOR]']
    for i in range(len(ids[:-1])):
        subset = content[ ids[i][1]:ids[i+1][0] ]

        d = re.compile('<a href="(.*?polsatsport.pl/wideo-kategoria.+?[^"]+)".*?>(.*)</a').findall(subset)
        
        
    
        if d:
            maind = d.pop(0)
            t=mTittle[i%2]%unicodePLchar(maind[1])
            out.append({'title':t,'url':maind[0],'img':''})
    
            for one in d:
                    t=sTittle[i%2]%unicodePLchar(one[1])
                    out.append({'title':t,'url':one[0],'img':''})
    
    return out

def getContent(url, type = 'magazyny', nextUrl = '', prevUrl = '', **kwargs):
    if type == 'magazyny':
        return getMagazyny()

    return []

def getContentVideos(url):
    content = getUrl(url)

    tds = re.compile('<article(.*?)</article>',re.DOTALL).findall(content)
    out=[]
    nextPage = False
    prevPage = False

    for td in tds:
        href = re.compile('href="(.*?)"',).findall(td)
        title = re.compile('alt="(.*?)"').findall(td)
        img = re.compile('src="(.*?)"').findall(td)

        if href and title:
            h = href[0]
            t = unicodePLchar(title[0].strip())
            i = img[0] if img else ''
            out.append({'url':h,'title':t,'img':i})
    if out:
        
        nextPage = re.compile('<a href="(.*?)" class=(?:"next-page ico"|"pagination__button button button--arrow-right")').findall(content) #  "pagination__button button button--arrow-right"')
        nextPage = nextPage[0] if nextPage else False
        prevPage = re.compile('<a href="(.*?)" class=(?:"prev-page ico"|"pagination__button button button--arrow-left")').findall(content) # = re.compile('href="(.*?)" class="pagination__button button button--arrow-left"').findall(content)
        
        
        
        
        
        
        
    #    (?:Filmweb\:|IMDb\:|Portal\:)    (?:"next-page ico"|"pagination__button button button--arrow-right")'
    #    href="https://www.polsatsport.pl/program/koloseum-magazyn-sportow-walki_1500573/" class="pagination__button button button--arrow-left"
        prevPage = prevPage[0] if prevPage else False

    return (out,(prevPage,nextPage))

url='http://www.polsatsport.pl/magazyn/cafe-futbol-06092015-dogrywka_6345047/'

def getVideos(url):
    content = getUrl(url)
    v={'msg':'Video link not found or not supported yet'}
    src = re.compile('<source data-src="(.*?)" type="video/mp4"').findall(content) #source data-src="https://redirector.redefine.pl/vm2movies/uxhwax8womb3f4pyvd85ni67h5x8zses.mp4" type
    if src:
        v={'msg':'','url':src[0]}
    return v

def test():
    out,pagination = get_games('http://www.livefootballol.me/video/england/')

    for one in out:
        vl = getVideos(one.get('url'))

  #  print vl

def _scanMagazyny():
    url='http://www.polsatsport.pl/program/atleci/'
    content = getUrl(url)
    out=[]
    magazyny = re.compile('<li class="disciplines-aside-item"><a href="(.*)" [^>]*>(.*)</a></li>').findall(content)

    for magazyn in magazyny:
        tmp = getUrl(magazyn[0])
        plot = re.compile('<div class="article-preview"(.*?)</div>',re.DOTALL).findall(tmp)
        plot = plot[0] if plot else ''

        if plot:
            plot = re.compile('<p><span>(.*?)</span></p>').findall(plot)
            plot = unicodePLchar(plot[0]) if plot else ''

        img=re.compile('<div class="fl-right">\s*<figure>\s*<img src="(.*?)"',re.DOTALL).findall(tmp)
        img = img[0] if img else ''
        out.append({'title':unicodePLchar(magazyn[1]),'url':magazyn[0],'plot':plot,'img':img})

    return out

def getMagazyny():
    out=[{'img': 'http://s.redefine.pl/dcs/o2/redefine/cp/nm/nm1vnqzacinsd1rhet1zkdr4wdptch7t.jpg',
        'plot': '',
        'title': 'Cafe Futbol',
        'url': 'http://www.polsatsport.pl/program/cafe-futbol/'},
        {'img': 'http://s.redefine.pl/dcs/o2/redefine/cp/2y/2y3ke55pagen5hdae7xv2v9vkzufmebn.jpg',
        'plot': '',
        'title': 'Puncher',
        'url': 'http://www.polsatsport.pl/program/puncher/'},
        {'img': 'https://s.redefine.pl/file/o2/redefine/cp/5c/5cq45o8izuz5ggguw2navjrkvaidfn5r.jpg',
        'plot': '',
        'title': 'Magazyn Fortuna 1 Ligi',
        'url': 'http://www.polsatsport.pl/program/magazyn-fortuna-1-ligi_1491920/'},
        
        {'img': 'https://ipla.pluscdn.pl/dituel/cp/44/44rgqax39mqsb1v3uuepan46uo44fb3y.png',
        'plot': '',
        'title': 'Magazyn koszykarski',
        'url': 'https://www.polsatsport.pl/program/magazyn-koszykarski/'},
        
        {'img': 'https://ipla.pluscdn.pl/dituel/cp/p8/p8par25wy336d3ynjs5gcgi4nrbmnqzo.jpg',
        'plot': '',
        'title': 'Atleci',
        'url': 'https://www.polsatsport.pl/program/atleci/'},
        
        {'img': 'https://ipla.pluscdn.pl/dituel/cp/dv/dv32n8jo8bsxox4xj8hjv65a1bk4xcgw.jpg',
        'plot': '',
        'title': 'Magazyn żużlowy',
        'url': 'https://www.polsatsport.pl/program/magazyn-zuzlowy_1499688/'},
        
        {'img': 'https://ipla.pluscdn.pl/dituel/cp/dv/dv32n8jo8bsxox4xj8hjv65a1bk4xcgw.jpg',
        'plot': '',
        'title': 'Magazyn żużlowy',
        'url': 'https://www.polsatsport.pl/program/magazyn-zuzlowy_1499688/'},
        
        
        
        
        {'img':'https://ipla.pluscdn.pl/dituel/cp/94/947554gazk1sxyuhv6zqzphrf4x8ecvb.png',
        'plot':'',
        'title': 'Koloseum',
        'url':'https://www.polsatsport.pl/program/koloseum-magazyn-sportow-walki_1500573/'}]
        
        
        
    url = 'https://www.polsatsport.pl/magazyny/'    
    content = getUrl(url)
    out=[]
    content = re.findall('section class(.+?)<\/section>',content)[0]
    
    ids = [(a.start(), a.end()) for a in re.finditer('<article class="news', content)]
    ids.append( (-1,-1) )
    out=[]

    for i in range(len(ids[:-1])):
        subset = content[ ids[i][1]:ids[i+1][0] ]
        dt=re.findall('href="([^"]+)">.*?img" src="([^"]+).*?news__title">([^<]+)<',subset)[0]
        
        out.append({'title':dt[2],'url':dt[0],'img':dt[1]})
        

    return out

def unicodePLchar(txt):
    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
