# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/panet.py
from imports 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 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 panet(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}, -1)
        self['menulist'] = m2list([])
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('ILive')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = 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.list_cat)

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

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            self.load_poster()
        elif self.info == 'list_episodes':
            self.load_poster()

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            self.load_poster()
        elif self.info == 'list_episodes':
            self.load_poster()

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

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

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        cat = [('Movies', 'http://www.panet.co.il/movies/'),
         #('Ramadan Series 2014', 'http://www.panet.co.il/series/category/34/1'),
         ('Turky Series', 'http://www.panet.co.il/series/category/17/1'),
         ('Egypt Series', 'http://www.panet.co.il/series/category/19/1'),
         ('Syrische und libanesische Series', 'http://www.panet.co.il/series/category/18/1'),
         ('Golf-Series', 'http://www.panet.co.il/series/category/21/1'),
         ('Mexikanische und internationale Series', 'http://www.panet.co.il/series/category/20/1'),
         ('Menbramj und Sonstiges', 'http://www.panet.co.il/series/category/27/1'),
         ('Kinderprogramme', 'http://www.panet.co.il/series/category/15/1'),
         #('Lustige Clips', 'http://www.panet.co.il/series/category/2/1'),
         ('Konzerte', 'http://www.panet.co.il/series/category/7/1')]
        for each in cat:
            title, url = each
            self.cat_list.append(cat_(title, url))

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

    def list_shows(self, url):
        self.info = 'list_shows'
        self.show_list = []
        req = urllib2.Request(url)
        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')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
#<a class="panet-thumbnail" href="(.*?)"><img src="(.*?)" alt="(.*?)"><div class="panet-title"
        shows = re.findall('<a class="panet-thumbnail" href="(.*?)"><img src="(.*?)" alt="(.*?)"><div class="panet-title"', response)
        print shows
        for each in shows:
            url, img, title = each
            url = str(url).replace('\\', '')
            url = 'http://www.panet.co.il' + url
            self.show_list.append(show_(title, url, img))

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

    def list_episodes(self, url):
        self.info = 'list_episodes'
        self.episodes_list = []
        req = urllib2.Request(url)
        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')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        episodes = re.findall('<a class="panet-thumbnail" href="(.*?)"><img src="(.*?)" alt="(.*?)"><div class="panet-title"', response, re.DOTALL)
        for each in episodes:
            url, img, title = each
            url = str(url).replace('\\', '')
            url = 'http://www.panet.co.il' + url
            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()

    def list_streams(self, url):
        self.streams_list = []
        vid_id = str(url).split('/')
        try:
            id = vid_id[7]
            new_url = 'http://www.panet.co.il/series/seriesLink/' + id
        except:
            id='no id'		
            new_url=url
        req = urllib2.Request(new_url)
        req.add_header('Host', 'www.panet.co.il')
        req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
        req.add_header('Accept-Encoding', 'gzip, deflate, sdch')
        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('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')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        print response
        stream = re.findall('"url":"(.*?)"', response)
        if stream:
            stream = str(stream[0]).replace('\\', '')
            self.play_dubaitv_vod(stream)
        else:#panetVod.loadVodPlayer("http://pms.panet.co.il/online/images/video_lib/movies/1872_pimg.jpg","http://vod-movies.panet.co.il/Toufahat-hawwa/1.mp4"
            stream=re.findall('panetVod.loadVodPlayer\(".*?","(.*?)",',response)
            print stream
            if stream:
                self.play_dubaitv_vod(stream[0])         

    def list_movies(self, url):
        self.info = 'list_movies'
        self.movies_list = []
        url = str(url) + '1'
        print url
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30')
        page = urllib2.urlopen(req)
        response = page.read()
        page.close()
        #movies = re.findall('panetVod.loadVodPlayer\\("(.*?)","(.*?)",340,255,false.*?itemprop="name">(.*?)</span>', response, re.DOTALL)
        movies=re.findall('<div class="panet-thumbnail"><a href="(.*?)"><img src="(.*?)" alt="(.*?)">',response,re.DOTALL)
        for each in movies:
            url,img,title = each
            url = 'http://www.panet.co.il' + url
            #print img
            self.movies_list.append(show_(title, url, img))

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

    def play_dubaitv_vod(self, 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)
            if 'series' in url:
                self.list_shows(url)
            else:
                self.list_movies(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
            url = str(selectedEntry)
            print url
            self.list_streams(url)
        elif self.info == 'list_movies':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            self.list_streams(url)
            #self.play_dubaitv_vod(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['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_movies':
            self.info = 'list_cat'
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        print jp_link
        tmp_image = jpg_store = '/tmp/1.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'
        jpg_name = '1.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'