# -*- 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


import json

import re,os
import xbmc
import requests
#import urllib
BASEURL = "https://www.laczynaspilka.pl/lista-filmow,1.html"
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 loguj(usrlnp, pwdlnp):
    return True


cdnurlx='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/subcompetition/filter?limit=9999&skip=0&competitionId='
cdnurl='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/match/list/by-subcompetition/DateDesc/'
freezurl="https://cdn.laczynaspilka.pl/freeze-frames/"    
vidurl='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/video/'

def GetCategory(url):
    import json
    #headers = {
    #'Host': 'www.laczynaspilka.pl',
    #
    #'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
    #
    #'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    #
    #'Accept-Language': 'en-US,en;q=0.9',}
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
        'Accept': 'application/json',
        'Accept-Language': 'pl',
        'Content-Type': 'application/json',
        'Origin': 'https://www.laczynaspilka.pl',
        'Connection': 'keep-alive',
        'Referer': 'https://www.laczynaspilka.pl/biblioteka/wideoteka',
        'TE': 'Trailers',
    }
    
    response = requests.get(url, headers=headers,verify=False).json()

    
    
    
    xbmc.log('@#@htmlhtml: %s' % str(url), LOGNOTICE)
    #response = requests.get(url, headers=headers, verify=False).json()
    #items = response["content"]["content"]["main"]["items"]
    items = response["items"]
    out=[]
    for item in items:
        if "footballCompetition" in item:
            tytul = item['nazwa']#["headline"]
            img = item["logo"]['url']
            img='https://cdn.laczynaspilka.pl/cms2/prod'+img
            id = item["id"]
            url=cdnurl+id
        else:
            tytul = item['title']#["headline"]
            url = item['url']#url#+'|'+tytul
            url='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/page/'+url.replace('/','%2F') if url.startswith('/') else url
            img=''
        out.append({'url':url,'title':tytul,'img':img,'code':''})
    return out
    
def getSubCateg(url,tyt):

    import json
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
        'Accept': 'application/json',
        'Accept-Language': 'pl',
        'Content-Type': 'application/json',
        'Origin': 'https://www.laczynaspilka.pl',
        'Connection': 'keep-alive',
        'Referer': 'https://www.laczynaspilka.pl/biblioteka/wideoteka',
        'TE': 'Trailers',
    }

    response = requests.get(url, headers=headers, verify=False).json()

    try:
        response2 = response['item']
    except:
        response2 = ''
    out=[]
    if "playlistItems" in response or "playlistItems" in response2:
        items = response['item']["playlistItems"]
        
        
        
    
    
        for item in items:
            tytul = item['title']
            url = item['url']
            url='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/page/'+url.replace('/','%2F') if url.startswith('/') else url
            img = item['banner']['background_images']['desktop']['url']
            img='https://cdn.laczynaspilka.pl/cms2/prod'+img
            nic = 'nic'
            if item['discriminator']=='VideoLibraryPlaylist':
                nic ='mat'
            out.append({'url':url+'|'+nic,'title':tytul,'img':img,'code':''})

    else:
        items = response['items']
        for item in items:
            if 'footballCompetition' in item:
                tytul = item['nazwa']
                id = item['id'] 
                img = item['logo']['url']
                img='https://cdn.laczynaspilka.pl/cms2/prod'+img
                url=cdnurl+id

                out.append({'url':url+'|nic','title':tytul,'img':img,'code':''})
            else:
                tytul = item['title']
                id = item['url']
                url = 'https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/page/'+id.replace('/','%2F')
                img = item["images"]['desktop']['url']
                img='https://cdn.laczynaspilka.pl/cms2/prod'+img
                out.append({'url':url+'|mat','title':tytul,'img':img,'code':''})

    return out    

def getMaterial(url,tyt):

    import json

    UA = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
        'Accept': 'application/json',
        'Accept-Language': 'pl',
        'Content-Type': 'application/json',
        'Origin': 'https://www.laczynaspilka.pl',
        'Connection': 'keep-alive',
        'Referer': 'https://www.laczynaspilka.pl/biblioteka/wideoteka',
        'TE': 'Trailers',
    }
    response = requests.get(url, headers=headers, verify=False).json()
    out=[]
    cdurl=''

    if "playlist" in response["item"]:
        items = response["item"]["playlist"]

        ids= '&'.join(['ids=%s' % (item["file"]['id']) for item in items])
        
        url='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/video/list?'+ids
        response = requests.get(url, headers=headers, verify=False).json()

        items = response["items"]
        for item in items:
            vid = item["cutvVideoHeader"]
            id = vid["id"]
            url = vidurl+id
            tytul = vid["title"]

            bb=vid["images"][0]["url"].replace('\\','/')
            cc = Changelettter(bb)

            img = freezurl+cc+'|User-Agent='+UA

            out.append({'url':url,'title':tytul,'img':img,'code':''})
    else:
        ids=''
        contents = response['item']['content']
        for content in contents:
            opis = content['headline']['text']
            items = content['video']

            ids+= '&'.join(['ids=%s' % (item["file"]['id']) for item in items])
            ids+='&'
        ids = re.sub('(\&)$','',ids) if ids.endswith('&') else ids
        url='https://bus20-api-bpp.laczynaspilka.pl/api/bpp/v1/video/list?'+ids
        response = requests.get(url, headers=headers, verify=False).json()

        items = response["items"]
        for item in items:
            opis = item['title']
            vid = item["cutvVideoHeader"]
            id = vid["id"]
            url = vidurl+id
            tytul = vid["title"]

            bb=vid["images"][0]["url"].replace('\\','/')
            cc = Changelettter(bb)

            img = freezurl+cc+'|User-Agent='+UA

            tyt ='[COLOR gold]'+opis+'[/COLOR] '+tytul
            opis2 ='[COLOR gold]'+opis+'[/COLOR][CR]'+tytul
            out.append({'url':url,'title':tyt,'img':img,'code':opis2})

    return out    
def getLink(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
        'Accept': 'application/json',
        'Accept-Language': 'pl',
        'Content-Type': 'application/json',
        'Origin': 'https://www.laczynaspilka.pl',
        'Connection': 'keep-alive',
        'TE': 'Trailers',
    }
    response = requests.get(url, headers=headers, verify=False).json()
    videomedias = response['item']['videoMedia']
    link=''
    for videomedia in videomedias:
        medias = videomedia['media']
        for media in medias:
            if media['mimeType'] == 'application/octet-stream':
                link = 'https://cdn.laczynaspilka.pl/pz/'+media['subpath']
                break
    return link

def Changelettter(txt):
    if type(txt) is not str:
        txt=txt.encode('utf-8')

    txt = txt.replace('\xc4\x85','%C4%85').replace('\xc4\x84','%C4%84')
    txt = txt.replace('\xc4\x87','%C4%87').replace('\xc4\x86','%C4%86')
    txt = txt.replace('\xc4\x99','%C4%99').replace('\xc4\x98','%C4%98')
    txt = txt.replace('\xc5\x82','%C5%82').replace('\xc5\x81','%C5%81')
    txt = txt.replace('\xc5\x84','%C5%84').replace('\xc5\x83','%C5%83')
    txt = txt.replace('\xc3\xb3','%C3%B3').replace('\xc3\x93','%C3%93')
    txt = txt.replace('\xc5\x9b','%C5%9B').replace('\xc5\x9a','%C5%9A')
    txt = txt.replace('\xc5\xba','%C5%BA').replace('\xc5\xb9','%C5%B9')
    txt = txt.replace('\xc5\xbc','%C5%BC').replace('\xc5\xbb','%C5%BB')
    return txt    
    
    
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.encode(encoding='utf-8', errors='strict')
    return link

def getContent(url,**kwargs):
    if not url: url = BASEURL
    content = getUrl(url)
    out = []
    tds = re.compile('<a (href="//www.youtube.com.*?)</a>',re.DOTALL).findall(content)
    nextPage = False
    prevPage = False

    for td in tds:
        href = re.compile('href="(.*?)"').findall(td)
        title = re.compile('data-title="(.*?)"').findall(td)
        date = re.compile('data-date="(.*?)"').findall(td)
        img=re.compile('<img src="(.*?)"').findall(td)
        if href and title:
            h = 'http:'+href[0]
            t = title[0].strip()
            i = img[0] if img else ''
            code = date[0] if date else ''
            out.append({'url':h,'title':t,'img':i,'code':code})

    if out:
        nextPage = re.compile('<a href="(http.*?)">Następna').findall(content)
        nextPage = {'urlp': nextPage[0]} if nextPage else False
        prevPage = re.compile('<a href="(http.*?)"> &laquo; Poprzednia').findall(content)
        prevPage = {'urlp': prevPage[0]} if prevPage else False

    return (out,(prevPage,nextPage))

def getVideos(ex_link):
    return {'msg':'','url':ex_link}
