# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/spox.py
from setup import *
from imports import *
from enigma import eTimer
cj = {}

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_(name, link, img, info):
    res = [(name,
      link,
      img,
      info)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


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


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


class spox(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,
         'red': self.exit,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('spox.com')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label(_(' '))
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.letter_list = []
        self.dir()
        self.onLayoutFinish.append(self.abc)

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

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

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

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

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

    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.currentList = 'menulist'
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.live_ids = ['5w44is9j2kg1exsezt1prbln',
         '15mr4d7sk5ozr19pg3wukpy6xy',
         '6hb4vxgg0v5h1wmeszxg6tj5d',
         '1kg3w2dghuz811gi8ievfcehbg',
         '17f2wdxjk7d3k1h5tzqxarsshg',
         '1afp49nwvibsa1odik6302ensg',
         '1qc5gbmew6d0f1le90szgf6nmz',
         '14ycunmhmyaly1ditl2qp9d3ll',
         'h74jgqrq4v531ja61e1ekl5ld']
        for id in self.live_ids:
            uri = 'http://fta.performfeeds.com/ftalivestream/3y0k606h5xy31p08hi6ldmirf/%s/' % id
            print uri
            getPage(uri, timeout=8, method='GET', headers={'User-Agent':'iPhone',
            'Host':'fta.performfeeds.com',
            'Origin':'http://player.performgroup.com',
            'Referer':'http://player.performgroup.com/fta/fta.html'}).addCallback(self.load_data_channels)

    def load_data_channels(self, data):
        self.index = 'load_data_channels'
        from datetime import datetime, timedelta
        import time
        import json
        if 'streams' in data:
            j = json.loads(data)
            parent = j['streams']
            for item in parent:
                id = str(item['streamId'])
                print id
                start = str(item['streamStartTime'])[:10]
                end = str(item['streamEndTime'])[:10]
                print start, end
                img = item['playerConfig']['slates']['low'].encode('utf-8')
                print img
                dt = datetime.fromtimestamp(int(start))
                dt = str(dt)[5:16]
                print dt
                title = item['description'].encode('utf-8')
                title = dt + ' : ' + title
                print title
                url = 'http://fta.performfeeds.com/livestreamlaunch/3y0k606h5xy31p08hi6ldmirf/%s/' % id
                print url
                self.letter_list.append(show_(title, url, img, None))

        self['menulist'].l.setList(self.letter_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def getxmlurl(self, data):
        self.index = 'load_data_channels'
        print 'i am here waiting for data'
        print data

    def ok(self):
        print self.index
        if self.index == 'load_data_channels':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            print uri
            params = {'_fmt': 'json',
             '_rt': 'c'}
            posti = urllib.urlencode(params)
            print posti
            uri += '?' + posti
            print uri
            cj = {}
            req = urllib2.Request(uri)
            req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
            req.add_header('Accept-Language', 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
            req.add_header('Cache-Control', 'max-age=0')
            req.add_header('Connection', 'keep-alive')
            req.add_header('Host', 'fta.performfeeds.com')
            req.add_header('Origin', 'http://fta.performfeeds.com/')
            req.add_header('Referer', 'http://player.performgroup.com/fta/fta.html')
            req.add_header('Upgrade-Insecure-Requests', '1')
            req.add_header('User-Agent', 'iPhone')
            page = urllib2.urlopen(req)
            response = page.read()
            page.close()
            print response
            fin_url = re.findall('"playerAlias":"hlshd","launcherURL":"(.*?)"', response)
            if fin_url:
                fin_url = 'http://127.0.0.1:88/hlsvariant://' + fin_url[0].replace('\\u0026', '&').replace('\\u003d', '=')
                self.play_that_shit(fin_url)

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

    def exit(self):
        print self.index
        if self.index == 'load_data_channels':
            self.close()
        else:
            self.index = 'load_data_channels'
            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            self.load_poster()

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/teledunet_poster.jpg'
        try:
            downloadPage(jp_link, tmp_image).addCallback(self.downloadPic, tmp_image)
        finally:
            print 'loaded'

    def show_cover(self):
        jpg_link = '/usr/lib/enigma2/python/Plugins/Extensions/teledunet/images/'
        jpg_name = 'no_cover.png'
        jpg_store = jpg_link + jpg_name
        if not os.path.exists(jpg_store):
            self.downloadPic(jpg_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 '[teledunet] 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 '[teledunet] no cover.. error'
        return

    def stream_not_found(self):
        message = self.session.open(MessageBox, _('Stream not available in your country'), MessageBox.TYPE_INFO, timeout=3)

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