'''
    Our Match Add-on
    Copyright (C) 2016 123456

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
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 xbmcgui
from resources.lib import dom_parser2

import re
import json
import requests

TIMEOUT = 10
UA      = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0'

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 main(name=None):
    out=[]
    c = getUrl('http://ourmatch.net')

    if name:
        #r = dom_parser2.parse_dom(c, 'li', {'class': 'header'})
        r = dom_parser2.parse_dom(c, 'li', {'class': 'sub-menu-list-item'})
        r = [i for i in r if '/%s/' % name.lower() in i.content]
        
        # <li class="sub-menu-list-item
    #    r = [i for i in r if 'title="%s"' % name in i.content]
    #    r = dom_parser2.parse_dom(r, 'li', {'class': 'hover-tg'})
    #    r = dom_parser2.parse_dom(r, 'a')
        for i in r:

            tyt = re.findall('>(.+?)<\/a>',i.content,re.DOTALL)#[0]
            href = re.findall('href="([^"]+)',i.content,re.DOTALL)#[0]
            if tyt and href:
                if '/span>' in tyt[0]:
                    continue
                else:
                    href = 'https://ourmatch.me'+href[0] if href[0].startswith('/') else href[0]
        #    out.append( {'title':i.content,'url':i.attrs['href']})
                    out.append( {'title':tyt[0],'url':href})
    else:
        r = dom_parser2.parse_dom(c, 'ul', {'class': 'sub-menu-list'})

        for i in r:
            if not 'sub-menu-list-item sub-menu-list-item-title' in i.content:
            #if 'role' in i.attrs:
            ##try:
            #    if i.attrs['role']=='group':
                continue
            #except:

            z=i.content
            #if 'competitions' in z:
            #    continue
            tyt= re.findall('<\/span>(.+?)<\/li>',z,re.DOTALL)[0].strip()
            #tyt = re.sub('(<.+?>)','',z)
            out.append( {'title':tyt,'url':tyt,'img':tyt.lower()+'.png'} )
    return out

def getMatches(url,ilo=None):
    
    out=[]
    np=False
    if 'loadmore' in url:
        npx,curp,maxp,posts = url.split('|')
        
        data = {
        'action': 'loadmore',
        'query': json.loads(posts),
        'page': int(curp)
        }
        headers = {
            'User-Agent': UA,
            'Accept': '*/*',
            'Accept-Language': 'pl,en-US;q=0.7,en;q=0.3',

            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Origin': 'https://ourmatch.me',
            'Connection': 'keep-alive',}
    
        c = requests.post('https://ourmatch.me/wp-admin/admin-ajax.php', headers=headers, data=data).text
        
        
        
        
        
        curp = int(curp)+1
        if curp<int(maxp):
            np = 'loadmore|{}|{}|{}'.format(str(curp),str(maxp),str(posts))
        #else:
        #    np=''
        
    else:
        if url == 'search':
            term = xbmcgui.Dialog().input(u'Search Our Match', type=xbmcgui.INPUT_ALPHANUM)
            if term: c  = getUrl('http://ourmatch.net/?s=%s' % term.lower().replace(' ','+'))
            else: quit()
        else:
            c = getUrl(url)
        
    results = parseDOM(c,'div', attrs={'class': "col-12 col-md-6 col-lg-4 match-info"})#[0]
    for result in results:
        a=''
        href = parseDOM(result,'a',ret='href')[0]
        img = parseDOM(result,'img',ret='src')[0]
    
        teams = re.findall('match-info__link-team__club-name">(.+?)<',result,re.DOTALL)
    
        title = ' vs '.join([(team.replace('\n','').replace('\t','')).strip() for team in teams])
        dt = (re.findall('match-info__link-date">(.+?)<',result,re.DOTALL)[0].replace('\n','').replace('\t','')).strip()
    
        out.append( {'title':'[COLOR blue]%s[/COLOR]   [COLOR khaki]%s[/COLOR]' % (title, dt), 'url':href,'img':img} )
    
    loadmore = re.findall('loadmore_params = (\{.*?\});',c,re.DOTALL)
    if loadmore:
        loadmorex=loadmore[0]
        loadmore=json.loads(loadmorex)
        curp = str(loadmore.get('current_page',None))
        maxp = str(loadmore.get('max_page',None))
        
        posts = json.dumps(loadmore.get('posts',None))
        np = 'loadmore|{}|{}|{}'.format(str(curp),str(maxp),str(posts))
    else:
        if 'loadmore' in url and np:
            pass
        else:
            try:
                np = re.findall('''<link\s*rel=['"]next['"]\s*href=['"]([^'"]+)''', c)[0]    
            except:
                pass
        
    return out,np

def getStreams(name,url,iconimage):
    out=[]
    c = getUrl(url)
    try: plot=re.findall('"description" content="(.+?)Full',c)[0].replace('.','[CR]')
    except: plot=''
    r = re.findall("\d+':\s*{embed:'([^}]+)", c)
    for i in r:
        try:
            src = re.findall('''src=['"]([^'"]+)''',i)[0]
            if '.jpg' in src:
                src= re.findall('''a href="(.+?)"''',i)[0]
            if not src.startswith('http'): src = 'https:' + src
            try: lang = re.findall('''lang:['"]([^'"]+)''',i)[0]
            except: lang = 'Unknown'
            try: name = re.findall('''['"]type['"]:['"]([^'"]+)''',i)[0]
            except: name = 'Unknown'
            try: quality = re.findall('''quality:['"]([^'"]+)''',i)[0]
            except: quality = 'Unknown'
            try: source = re.findall('''source:['"]([^'"]+)''',i)[0]
            except: source = 'Unknown'
            out.append( {'title':'%s - %s - %s - %s' % (name, quality, lang, source),'url':src,'img':iconimage,'plot':plot } )
        except: pass
    return out
    
def getUefa(url):
    html=getUrl(url)
    part2=re.findall('"hide">(.+?)<',html)[0]
    link2=urllib_parse.unquote(url)
    link2=re.findall("sharingurl=(.+?)&skin",link2)[0]
    html=getUrl(link2)
    result=re.findall('"vpl-list-item js-vpl-video vpl-active "(.+?)application',html,re.DOTALL)[0].replace('&quot;','"')
    video_url=re.findall('"videoURLhls":"(.+?)"',result)[0]
    videourl=video_url+'?hdnea='+part2    
    return videourl
    
def play(name,url):

    import resolveurl as urlresolver
    if urlresolver.HostedMediaFile(url).valid_url() and 'viuclips' not in url: 
        try:
            url = urlresolver.HostedMediaFile(url).resolve()
        except:
            pass
    else:
        if 'PopUpIframe' in url:
            url=url.replace('/player/PopUpIframe/','/embed/')
        link  = getUrl(url).replace("\'",'"')
        match = re.compile('<source src="(.+?)" type="video/mp4" class="mp4-source"/>').findall(link)
        match_cv = re.compile('hls:"//(.*?)"').findall(link) #.replace('0.m3u8','720p.m3u8')
        #match_cv2 = re.compile("""hls\:\\['"](.+?)\\['"]""").findall(link)    
        match_cv2 = re.findall("""hls\:\\['"](.+?)\\['"]""",link,re.DOTALL)


        
        for url in match:
            name = name
            url  = 'https:'+url
        if 'media.content-ventures.com' in url:
            url='http://' + match_cv[0]
        if 'oms.' in url or 'videostreamlet' in url or 'veuclips' in url or 'viuclips' in url or 'vidupstream' in url:
            if match_cv2:
                url='http://' + match_cv2[0]    
            else:
                url='http://' + match_cv[0]
        if 'upclips' in url or 'streamatus' in url:
            try:
                link=link.replace("\'",'"')
                url=re.findall("""hlsSource\:|source\:['"](.+?)['"]""",link,re.DOTALL)[0]
            except:
                url=re.findall("""src:\s*['"](.+?)['"].+?type:\s*['"]application""",link,re.DOTALL)[0]#src: "
            if url.startswith('//'): url = 'https:' + url
        if 'uefa.com' in url:
            url=getUefa(url)
    stream_url = url
    if 'vidstreamup' in stream_url or 'tovidit.' in stream_url:      
        import meczykipl
        stream_url=meczykipl.getUpclips(stream_url)    
    return stream_url
