# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/myaz.py
from imports import *
from about import *
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'

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


def show_all_(name, link, image, info):
    res = [(name,
      link,
      image,
      info)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class myvideoaz(Screen):

    def __init__(self, session):
        global old_ref
        self.session = 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()
        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(_('About'))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label('')
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('myvideo.az')
        self.currentList = 'menulist'
        self.menulist = []
        self.dir()
        self.index = ''
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        url = 'http://www.myvideo.az/c/livetv'
        cj = {}
        getPage(url, timeout=15, method='GET', cookies=cj, headers={'Cookie': 'PHPSESSID=qm02kshtchc38dh72hvhqdah61;',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
         'Accept-Encoding': 'gzip, deflate, sdch',
         'Connection': 'keep-alive',
         'Host': 'www.myvideo.az',
         'Referer': 'http://www.myvideo.az/',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
         'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_channels, cj)

    def about(self):
        self.about()

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_channels':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_channels':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_channels':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_channels':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def get_channels(self, data, cj):
        self.index = 'get_channels'
        print cj
        self.chan_list = []
        channels = re.findall('<div class="livetv_grid_item">.*?<a href="(.*?)" title="(.*?)" >.*?<div class="tv_logo" style="background-image:url\\(\'(.*?)\'\\);" alt', data, re.DOTALL)
        print channels
        for url, title, img in channels:
            channelname = url.replace('tv/', '')
            url = 'http://www.myvideo.az/' + url
            img = 'http://www.myvideo.az' + img
            self.chan_list.append(show_all_(title, url, img, channelname))

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

    def get_params(self, data):
        self.index = 'get_params'
        channelname = self['menulist'].getCurrent()[0][3]
        server = re.findall("'srv':'(.*?)'", data)
        token = re.findall("'token':'(.*?)'", data)
        if server and token:
            final_url = 'http://127.0.0.1:88/hlsvariant://' + server[0] + channelname + '/index.m3u8?token=' + token[0] + ' headers={"Cookie": "flusession=ewS79OzwPw2O9646et7M1wM7ANLQ0NhUfA-cX7ixccR2i4j8ANH8ysSAXrmiunW2Dl22jGUmOw_pnOcixwHF8g**; Version=1; Expires=Fri, 18-Sep-2015 04:32:32 GMT; Max-Age=36000;"}'
            self.play_channel(final_url)

    def play_channel(self, data):
        selected = self['menulist'].getCurrent()[0][0]
        self.index = 'player'
        sref = eServiceReference(4097, 0, data)
        sref.setName(selected)
        self.session.nav.playService(sref)
        self.hide()

    def ok(self):
        if self.index == 'get_channels':
            url = self['menulist'].getCurrent()[0][1]
            getPage(url, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
             'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_params)

    def exit(self):
        if self.index == 'get_channels':
            self.close()
        elif self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'get_channels'
            self['menulist'].l.setList(self.chan_list)
            self['menulist'].l.setItemHeight(40)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/albatros/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 = '/tmp/albatros/poster.jpg'
        jpg_name = '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 '[Albatros] 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 '[WWE] no cover.. error'
        return

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