# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/dubaitv.py
from imports import *
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
COOKIEFILE = '/tmp/cookie_dubai.txt'
cookie = {}

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 episodes_(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


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


class dubaitv(Screen):

    def __init__(self, session):
        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,
         'yellow': self.about,
         'blue': self.dnitnow}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label('')
        self['name'] = Label('Plugin Auswahl')
        self['poster'] = Pixmap()
        self['title'] = Label('Dubaitv')
        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.list_cat)

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

    def dnitnow(self):
        if JobManagerInstalled and self.check == 'letter_movie':
            self.dnfile = 'True'
            link = self['menulist'].getCurrent()[0][1]
            self.filmname = self['menulist'].getCurrent()[0][0]

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

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

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

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

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        cat = [('Ramadan 2015', 'http://admin.mangomolo.com/analytics/index.php/plus/category?id=205393&o=category&user_id=71&p=all&limit=21', 'http://admin.mangomolo.com/analytics/uploads/71/ramadan-icon1.png'),
         ('Drama', 'http://admin.mangomolo.com/analytics/index.php/plus/category?id=30348&o=category&user_id=71&p=all&limit=21', 'http://admin.mangomolo.com/analytics/uploads/71/drama.png'),
         ('Documentaries', 'http://admin.mangomolo.com/analytics/index.php/plus/category?id=30364&o=category&user_id=71&p=all&limit=21', 'http://admin.mangomolo.com/analytics/uploads/71/documentaries.png'),
         ('Entertainment', 'http://admin.mangomolo.com/analytics/index.php/plus/category?id=30350&o=category&user_id=71&p=all&limit=21', 'http://admin.mangomolo.com/analytics/uploads/71/entertainment.png'),
         ('National Day', 'http://admin.mangomolo.com/analytics/index.php/plus/category?id=30590&o=category&user_id=71&p=all&limit=21', 'http://admin.mangomolo.com/analytics/uploads/71/national%20day.png'),
         ('Video Clips', 'http://admin.mangomolo.com/analytics/index.php/plus/category?id=30360&o=category&user_id=71&p=all&limit=21', 'http://admin.mangomolo.com/analytics/uploads/71/videoclips.png'),
         ('Religion', 'http://admin.mangomolo.com/analytics/index.php/plus/category?id=30349&o=category&user_id=71&p=all&limit=21', 'http://admin.mangomolo.com/analytics/uploads/71/reliion.png'),
         ('Sports', 'http://admin.mangomolo.com/analytics/index.php/plus/category?id=30347&o=category&user_id=71&p=all&limit=21', 'http://admin.mangomolo.com/analytics/uploads/71/sports.png')]
        for each in cat:
            title, url, img = each
            self.cat_list.append(show_(title, url, img))

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

    def list_shows(self, url):
        self.info = 'list_shows'
        self.show_list = []
        cj = {}
        getPage(url, timeout=15, method='GET', cookies=cj, headers={'Accept-Language': 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4',
         'Accept-Encoding': 'gzip, deflate, sdch',
         'Accept': 'application/json, text/javascript, */*; q=0.01',
         'Referer': 'http://www.dcndigital.ae/',
         'Origin': 'http://www.dcndigital.ae',
         'Host': 'admin.mangomolo.com',
         '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'}).addCallback(self.list_it, cj)

    def list_it(self, data, cj):
        global cookie
        print data
        cookie = cj
        print cookie
        import json
        j = json.loads(data)
        parent = j['results']
        for item in parent:
            title = str(item['title_en'])
            url = str(item['id'])
            img = 'http://admin.mangomolo.com/analytics/' + str(item['cover'])
            self.show_list.append(show_(title, url, img))

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

    def list_episodes(self, url):
        self.info = 'list_episodes'
        self.episodes_list = []
        print cookie
        print 'this is the id parsed to post: %s' % url
        uri = 'http://admin.mangomolo.com/analytics/index.php/plus/show'
        body = urllib.urlencode({'user_id': '71',
         'show_id': url,
         'season': 'false',
         'channel_userid': 'false'})
        stuff = {'mango_ci_session': 'a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%2202568c4d2fcee72c0b5a32d9aa2a35e6%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A12%3A%2279.207.50.24%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A18%3A%22Twisted+PageGetter%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1435687827%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D39aad27323c11f9bbab3e6d2ecd5415c'}
        getPage(uri, timeout=15, method='POST', postdata=body, cookies=cookie, headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
         'Connection': 'keep-alive',
         'Accept-Language': 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4',
         'Accept-Encoding': 'gzip, deflate',
         'Accept': 'application/json, text/javascript, */*; q=0.01',
         'Referer': 'http://www.dcndigital.ae/',
         'Origin': 'http://www.dcndigital.ae',
         'Host': 'admin.mangomolo.com',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'}).addCallback(self.list_episodes1)

    def list_episodes1(self, data):
        print 'data at list_episodes1'
        import json
        j = json.loads(data)
        parent = j['videos']
        for item in parent:
            title = str(item['title_en'])
            url = str(item['url'])
            img = 'http://admin.mangomolo.com/analytics/' + str(item['img'])
            self.episodes_list.append(show_(title, url, img))

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

    def play_movie(self, link):
        if link:
            link = link.replace('\\', '')
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            sref = eServiceReference(4097, 0, link)
            sref.setName(selectedName)
            self.session.open(MoviePlayer, sref)

    def ok(self):
        if self.info == 'list_cat':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.list_shows(url)
        elif self.info == 'list_shows':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.list_episodes(url)
        elif self.info == 'list_episodes':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            selectedEntry = str(selectedEntry).replace('\\', '')
            url = 'rtmp://dmi.mangomolo.com/vod/_definst_/mp4:' + str(selectedEntry)
            print url
            self.play_movie(url)

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            if fileExists('/tmp/dubaitv_poster.jpg'):
                os.system('rm -r /tmp/dubaitv_poster.jpg')
            self.close(self.session, 'exit')
        elif self.info == 'list_shows':
            self.info = 'list_cat'
            self['blue'].hide()
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'list_episodes':
            self.info = 'list_shows'
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'list_streams':
            self.info = 'list_episodes'
            self['blue'].hide()
            self['menulist'].l.setList(self.episodes_list)
            self['menulist'].l.setItemHeight(40)

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

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


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


def Plugins(path, **kwargs):
    global plugin_path
    plugin_path = path
    return [PluginDescriptor(name='dubaitv', description='dubaitv Streamer', where=[PluginDescriptor.WHERE_PLUGINMENU], fnc=main, icon='plugin.png')]