from imports import *
from Tools.Directories import fileExists, pathExists

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 cat_(letter, link):
    res = [(letter, link)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 26), font=4, text=letter, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class stadium_live(Screen):

    def __init__(self, session):
        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['title'] = Label('StadiumLive')
        self['text'] = Label('')
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        self.onLayoutFinish.append(self.abc)

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

    def jobix(self):
        if JobManagerInstalled:
            self.session.open(JobManagerFrontEnd)

    def up(self):
        self[self.currentList].up()
        os.system('rm /media/hdd/stadium.flv')
        os.system('killall -9 rtmpdump')

    def down(self):
        self[self.currentList].down()
        os.system('rm /media/hdd/stadium.flv')
        os.system('killall -9 rtmpdump')

    def left(self):
        self[self.currentList].pageUp()

    def right(self):
        self[self.currentList].pageDown()

    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 abc(self):
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.genre_name = 'sports'
        url = 'http://stadium-live.biz/'
        print url
        getPage(url, method='GET', headers={'Host': 'www.stadium-live.biz',
         'Content-Type': 'application/x-www-form-urlencoded',
         'UserAgent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'}).addCallback(self.load_data_channels)

    def load_data_channels(self, data):
        print 'got data - now processing live_list'
        self.letter_list = []
        print data
        m = re.findall('<td width=".." height=".."><p class="sdfsf">(.*?)</td>.*?<td width="..." class="sdfsf">(.*?)</td>.*?<td width=".*?" class="cvxcv">.*?<p><a target="_parent" href="(.*?)"><span class="Linkch">(.*?)</span></a></p>', data, re.DOTALL)
        matches = re.findall('<td width=".." height=".."><p class="sdfsf">(.*?)</td>\n<td width="..." class="sdfsf">(.*?)</td>\n<td width=".*?" class="cvxcv">\n<p><a target="_parent" href="(.*?)"><span class="Linkch">(.*?)</span></a></p>', data)
        matches1 = re.findall('<td width=".." height="32"><p class="sdfsf">(.*?)</td>\n<td width="..." class="sdfsf">(.*?)</td>\n<td width=".*?" class="cvxcv">\n<p><a target="_parent" href=".*?"><span class="Linkch">.*?</span></a></p>\n<p><a target="_parent" href="(.*?)"><span class="Linkch">(.*?)</span></a></p>', data)
        print m
        for each in m:
            time, match, url, linkname = each
            match = match.replace('&nbsp;', ' ').replace('\xa8\xb9', '\xc3\xbc').replace(',', '')
            name = time + ' ' + match + ':' + linkname
            print name
            url = 'http://stadium-live.biz/' + url
            self.letter_list.append(cat_(str(name), url))

        for each in matches1:
            time, match, url, linkname = each
            match = match.replace('&nbsp;', ' ').replace('\xa8\xb9', '\xc3\xbc').replace(',', '')
            name = time + ' ' + match + ':' + linkname
            print name
            url = 'http://stadium-live.biz/' + url
            self.letter_list.append(cat_(str(name), url))

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

    def ok(self):
        if self.check == 'abc':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            uri = selectedEntry
            print uri
            req = urllib2.Request(uri)
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
            req.add_header('Referer', 'http://www.stadium-live.com/')
            try:
                page = urllib2.urlopen(req)
                res = page.read()
            except:
                print 'framecode not available'
#                                   <iframe src="ch_138code.html" id="iframe1" scrolling="no" width="728" height="410" frameborder="0"  border="0" allowfullscreen>
            next_page = re.findall('<iframe src="(.*?)" id="iframe1" scrolling="no" width="..." height="..." frameborder="0"  border="0"', res)
            if next_page:
                next_page = 'http://stadium-live.biz/' + next_page[0]
                req = urllib2.Request(next_page)
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
                req.add_header('Referer', 'http://www.stadium-live.com/')
                try:
                    page = urllib2.urlopen(req)
                    response = page.read()
                except:
                    response = ''
#                                              <script type="text/javascript" src="http://www.playerapp1.pw/channel.php?file=138&width=720&height=400&autostart=true"></script>
                update_parameter = re.findall('<script type="text/javascript" src="(.*?)"></script>', response)
                if update_parameter:
                    uri = update_parameter[0]
                    file = re.findall('channel.php\?file=(.*?)&width',uri)
                    req = urllib2.Request(uri)
                    req.add_header('Host', 'www.playerapp1.pw')
                    req.add_header('Referer', 'http://stadium-live.biz/ch_127code.php')
                    page = urllib2.urlopen(req)
                    response = page.read()
                    print 'huch'
                    hdcast_page = re.findall('<iframe src="(.*?)" width=', response)
                    if hdcast_page:
                        uri = hdcast_page[0]
                        print uri
                        req = urllib2.Request(uri)
                        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
                        req.add_header('Host', 'www.playerapp1.pw')
                        req.add_header('Referer', 'http://stadium-live.biz/ch_127code.php')
                        page = urllib2.urlopen(req)
                        response = page.read()
                        print response
                        streamer_encoded = re.findall('<input type="hidden" id=".*?" value="(.*?)" />', response)
                        if streamer_encoded:
                            print streamer_encoded
                            streamer=base64.b64decode(streamer_encoded[2])
                            streamer=base64.b64decode(streamer)
                            print streamer
                            streamer=base64.b64decode(streamer)
                            print streamer
                            #streamer=base64.b64decode(streamer)							
                            #print streamer
                            host=streamer.split('/')
                            pageurl = hdcast_page[0].replace('%2F', '/').replace('%3D', '=')
                            final='http://127.0.0.1:88/hlsvariant://' + streamer + ' headers={"User-Agent":"stagefright","Host":"'+host[2]+'","Origin":"http://www.playerapp1.pw","Referer":"%s"}' % pageurl                           
                            self.play_that_shit(final)

    def play_that_shit(self, data):
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def exit(self):
        os.system('rm /media/hdd/stadium.flv')
        os.system('killall -9 rtmpdump')
        self.close()

    def load_poster_teledunet(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/highlive_poster.jpg'
        try:
            downloadPage(jp_link, tmp_image).addCallback(self.downloadPic, tmp_image)
        finally:
            print "Error: can't find file or read data"

    def show_cover(self):
        jpg_link = '/usr/lib/enigma2/python/Plugins/Extensions/HighLive/images/'
        jpg_name = 'no_cover.png'
        jpg_store = jpg_link + jpg_name
        if not os.path.exists(jpg_store):
            self.downloadPic(file_name, jpg_store)
        else:
            self.poster_resize(jpg_store)

    def downloadPic(self, data, jpg_store):
        if fileExists(jpg_store):
            self.poster_resize(jpg_store)
        else:
            print '[bkssport_live] logo not found'

    def poster_resize(self, poster_path):
        self['poster'].instance.setPixmap(None)
        self['poster'].hide()
        sc = AVSwitch().getFramebufferScale()
        self.picload = ePicLoad()
        size = self['poster'].instance.size()
        self.picload.setPara((size.width(),
         size.height(),
         sc[0],
         sc[1],
         False,
         1,
         '#FF000000'))
        if self.picload.startDecode(poster_path, 0, 0, False) == 0:
            ptr = self.picload.getData()
            if ptr != None:
                self['poster'].instance.setPixmap(ptr)
                self['poster'].show()
            else:
                print '[bkssport_live] no cover.. error'
        return

    def stream_not_found(self):
        message = self.session.open(MessageBox, _('Stream not found, try again later on'), MessageBox.TYPE_INFO, timeout=3)

    def errorload2(self, error):
        print '[bkssport_live] error %s' % error
        count_movies = len(self.letter_movielist)
        self.loading_ok = True
        self.loading = 0
        self.count = 0

    def errorload(self, error):
        print error

    def dir(self):
        if not pathExists('/tmp/highlive/'):
            os.system('mkdir /tmp/highlive/')
        else:
            print '[bkssport_live] /tmp/highlive/ allready present'


def main(session, **kwargs):
    session.open(bkssport_live)


def Plugins(path, **kwargs):
    global plugin_path
    plugin_path = path
    return [PluginDescriptor(name='Bkssport - Livestreams', description='watch live events', where=[PluginDescriptor.WHERE_PLUGINMENU], fnc=main, icon='plugin.png')]