from setup import *
from imports import *

class m2list(MenuList):

    def __init__(self, list):
        MenuList.__init__(self, list, False, eListboxPythonMultiContent)
        self.l.setFont(0, gFont('Regular', 14))
        self.l.setFont(1, gFont('Regular', 16))
        self.l.setFont(2, gFont('Regular', 18))
        self.l.setFont(3, gFont('Regular', 20))
        self.l.setFont(4, gFont('Regular', 22))
        self.l.setFont(5, gFont('Regular', 24))
        self.l.setFont(6, gFont('Regular', 26))
        self.l.setFont(7, gFont('Regular', 28))
        self.l.setFont(8, gFont('Regular', 32))


def show_(letter, link, img):
    res = [(letter, link, img)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, text=letter, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class wizihd(Screen):

    def __init__(self, session):
        global old_ref
        sz_w = getDesktop(0).size().width()
        if sz_w == 1920:
            if config.Albatros.skin.value=='1':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/defaultListScreen_new.xml"
            elif config.Albatros.skin.value=='2':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin2/defaultListScreen_new.xml"
            elif config.Albatros.skin.value=='3':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin3/defaultListScreen_new.xml"
        else:
            if config.Albatros.skin.value=='1':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/defaultListScreen.xml"
            elif config.Albatros.skin.value=='2':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin2/defaultListScreen.xml"
            elif config.Albatros.skin.value=='3':
                path = "/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin3/defaultListScreen.xml"
        with open(path, 'r') as f:
            self.skin = f.read()
            f.close()
        self.session = session
        Screen.__init__(self, session)
        self['actions'] = ActionMap(['OkCancelActions',
         'ColorActions',
         'DirectionActions',
         'MovieSelectionActions'], {'up': self.up,
         'down': self.down,
         'left': self.left,
         'right': self.right,
         'ok': self.ok,
         'cancel': self.exit,
         'red': self.exit}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['title'] = Label('wizihd')
        self['name'] = Label('')
        self['text'] = Label('')
        self['poster'] = Pixmap()
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.index = ''
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.category)

    def about(self):
        self.session.open(AboutScreen)

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def switchList(self):
        if self.currentList == 'menulist':
            self['ButtonBlue'].hide()
            self['TextBlue'].hide()
            self['menulist'].selectionEnabled(0)
            self.currentList = 'menulist2'
            self.check = 'abc'
        else:
            self['ButtonBlue'].show()
            self['TextBlue'].show()
            self['menulist'].selectionEnabled(1)
            self.currentList = 'menulist'
            self.check = 'letter_movie'

    def category(self):
        self.index = 'cat'
        self.cat_list = []
        cat = [('http://wizhdsports.to/sport/NFL', 'http://wizhdsports.to/images/02061406341.png', 'NFL'),
         ('http://wizhdsports.to/sport/Football', 'http://wizhdsports.to/images/2.png', 'Football'),
         ('http://wizhdsports.to/sport/Cricket', 'http://wizhdsports.to/images/11.png', 'Cricket'),
         ('http://wizhdsports.to/sport/Tennis', 'http://wizhdsports.to/images/4.png', 'Tennis'),
         ('http://wizhdsports.to/sport/Boxing', 'http://wizhdsports.to/images/3.png', 'Boxing'),
         ('http://wizhdsports.to/sport/Golf', 'http://wizhdsports.to/images/5.png', 'Golf'),
         ('http://wizhdsports.to/sport/Motorsport', 'http://wizhdsports.to/images/6.gif', 'Motorsport'),
         ('http://wizhdsports.to/sport/Rugby', 'http://wizhdsports.to/images/8.gif', 'Rugby'),
         ('http://wizhdsports.to/sport/NHL', 'http://wizhdsports.to/images/10.png', 'NHL'),
         ('http://wizhdsports.to/sport/NBA', 'http://wizhdsports.to/images/nba.gif', 'NBA'),
         ('http://wizhdsports.to/sport/Darts', 'http://wizhdsports.to/images/darts.png', 'Darts'),
         ('http://wizhdsports.to/sport/WWE', 'http://wizhdsports.to/images/wwe.gif', 'WWE'),
         ('http://wizhdsports.to/sport/Horse-Racing', 'http://wizhdsports.to/images/2511150527horse.gif', 'Horse Racing'),
         ('http://wizhdsports.to/sport/UFC', 'http://wizhdsports.to/images/2511150639ufc.gif', 'UFC'),
         ('http://wizhdsports.to/sport/Other', 'http://wizhdsports.to/images/0801160315other.gif', 'Other'),
         ('http://wizhdsports.to/sport/Baseball', 'http://wizhdsports.to/images/2902160718ball.gif', 'Baseball')]
        for url, img, title in cat:
            self.cat_list.append(show_(title, url, img))

        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)

    def get_matches(self, data):
        self.index = 'matches'
        self.match_list = []
        print data
        #matches = re.findall('<div class="match" id="match.*?">.*?<span id="startTime.*?Span">.*?(\\d{2}[:]\\d{2})</span>.*?<span id="endTime.*?Span">.*?(\\d{2}[:]\\d{2})</span>.*?<div class="name">(.*?)</div>.*?onClick="javascript:top\\.location\\.href=\'(.*?)\';">', data, re.DOTALL)
        matches=re.findall('<span class=\'fa fa-clock-o\'></span>(.*?)</div>.*?<div class=\'col-md-6\'>(.*?)</div>.*?<div class=\'col-md-2\'>(.*?)</div>.*?<blink><font color=\'.*?\'>(.*?)<span class.*?<a href=\'(.*?)\'><div class',data,re.DOTALL)
        if matches:
            print matches
            for m_time,m_title,m_genre,m_status,m_url in matches:
                title = m_time + ' : ' + m_title + ' : ' + m_status
                self.match_list.append(show_(title, m_url, None))

            self['menulist'].l.setList(self.match_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        return

    def get_link(self, data):
        print data
        link = re.findall('<iframe frameborder=.*?src="(.*?)" name="iframe_a"', data)
        print link
        if link:
            getPage(link[0], timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_id, link)

    def get_id(self, data, url):
        id = re.findall("<script type='text/javascript'>id='(.*?)'.*?src='http://static.bro.adca.st/broadcast/player3.js'></script>", data)
        print id
        if id:
            id = id[0]
            url = 'http://bro.adca.st/stream.php?id=' + id + '&cache=4&width=100%&height=100%&stretching=uniform&p=1&c=0'
            print url
            getPage(url, timeout=8, method='GET', headers={'Referer': url,
             'Host': 'bro.adca.st',
             'Referer':'http://wizhdsports.to/live/stream12.php',
             'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_p2purl, url)
        else:
            id = re.findall("id='(.*?)'.*?src='http://weplayer.pw/player.js'></script>", data)
            if id:
                id = id[0]
                url = 'http://weplayer.pw/stream.php?id=' + id
                print url
                getPage(url, timeout=8, method='GET', headers={'Referer': url,
                 'Host': 'weplayer.pw',
                 'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
                 'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_p2purl, url)

    def get_p2purl(self, data, url):
        import base64
        print data
        curl = re.findall('trap = "(.*?)";', data)
        if curl:
            print curl
            new_url = base64.b64decode(curl[0])
            print new_url
            token_url = 'http://bro.adca.st/fckymom.php'
            getPage(token_url, timeout=8, method='GET', headers={'Host':'bro.adca.st','Referer':'http://bro.adca.st/','X-REQUESTED-WITH':'XMLHttpRequest'}).addCallback(self.get_final_link, url, new_url) 

    def get_final_link(self, data, url, new_url):
        print data
        token = re.findall('\\{"rumba":"(.*?)"\\}', data)
        print token
        if token:
            play_link = new_url + 'SDqKTkNGus24djDc9ikBaQ'#token[0] #'SDqKTkNGus24djDc9ikBaQ'#
            print play_link
            self.play_that_shit(play_link, url)

    def result(self, data):
        print data
        self.play_that_shit(data, None)
        return

    def play_that_shit(self, data, url):
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        host = data.split('/')[2]
        print host
        print url
        print data
        p2plink = 'http://127.0.0.1:88/hls://' + data + ' headers={"Host":"'+host+'","Referer":"'+url+'","Accept":"*/*","Accept-Encoding":"gzip, deflate, sdch","Accept-Language":"de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4","Connection":"keep-alive","Cookie":"__cfduid=df594ee4837b39b1384b7cafd69f216401479898045","User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36","X-Requested-With":"ShockwaveFlash/23.0.0.207"}'
        print p2plink
        sref = eServiceReference(4097, 0, p2plink)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def ok(self):
        if self.index == 'cat':
            link = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(link, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_matches)
        elif self.index == 'matches':
            link = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(link, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_link)

    def exit(self):
        if self.index == 'matches':
            self.index = 'cat'
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        else:
            self.close()