# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/farfesh.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 farfesh(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['poster'] = Pixmap()
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self['title'] = Label('farfesh')
        self['text'] = Label('')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.content_list = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        self.content_list = []
        self.onLayoutFinish.append(self.load_data_channels)

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

    def up(self):
        self[self.currentList].up()
        if self.currentList == 'menulist':
            self.load_poster()

    def down(self):
        self[self.currentList].down()
        if self.currentList == 'menulist':
            self.load_poster()

    def left(self):
        self[self.currentList].pageUp()
        if self.currentList == 'menulist':
            self.load_poster()

    def right(self):
        self[self.currentList].pageDown()
        if self.currentList == 'menulist':
            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 load_data_channels(self):
        self.check = 'abc'
        self.letter_list = []
        self.letter_list.append(show_('Movies', 'http://www.farfesh.com/Video.asp?ZoneID=1&Chosen_ID=', 'http://www.farfesh.com/images/aflam.jpg'))
        self.letter_list.append(show_('Series', 'http://www.farfesh.com/MosalsalatPage.asp?PgCurrId=FlM.n.077.1.&SessId=N20O102NO1', 'http://www.farfesh.com/images/mosalsalat.jpg'))
        self.letter_list.append(show_('The X Factor', 'http://www.farfesh.com/Video.asp?ZoneID=451', 'http://www.farfesh.com/images/x-factor.jpg'))
        self.letter_list.append(show_('The Voice', 'http://www.farfesh.com/Video.asp?ZoneID=418', 'http://www.farfesh.com/images/the_voice.jpg'))
        self.letter_list.append(show_('Magic', 'http://www.farfesh.com/Video.asp?ZoneID=8', 'http://www.farfesh.com/images/se7er.jpg'))
        self.letter_list.append(show_('Video Talents', 'http://www.farfesh.com/Video.asp?ZoneID=7', 'http://www.farfesh.com/images/mawaheb.jpg'))
        self.letter_list.append(show_('Funny Clips', 'http://www.farfesh.com/Video.asp?ZoneID=3', 'http://www.farfesh.com/images/maqate3mod7eky.jpg'))
        self.letter_list.append(show_('The Winner Is', 'http://www.farfesh.com/Video.asp?ZoneID=622', 'http://www.farfesh.com/images/thewinneris.jpg'))
        self.letter_list.append(show_('Kids', 'http://www.farfesh.com/Kids.asp', 'http://www.farfesh.com/images/atfal.jpg'))
        self.letter_list.append(show_('AllMosalsalatRamadan', 'http://www.farfesh.com/AllMosalsalatRamadan.asp', 'http://www.farfesh.com/images/aflam.jpg'))
        self['menulist'].l.setList(self.letter_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()

    def ok(self):
        print self.check
        if self.check == 'abc':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            uri = selectedEntry
            if selectedName == 'Movies':
                i = 1
                for i in range(1, 28):
                    uri = uri + str(i)
                    print uri
                    getPage(uri, method='GET', headers={'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.list_content)
                    i += 1
                    uri = selectedEntry

            else:
                getPage(uri, method='GET', headers={'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.list_content)
        elif self.check == 'listcontent':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            getPage(selectedEntry, method='GET', headers={'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.get_player_url, selectedName)
        elif self.check == 'series':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            getPage(selectedEntry, method='GET', headers={'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.list_series, selectedName)
        elif self.check == 'series1':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            print selectedEntry
            getPage(selectedEntry, method='GET', headers={'Host': 'www.farfesh.com',
             '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.get_player_url, selectedName)

    def list_content(self, data):
        self.check = 'listcontent'
        content = re.findall('<TD width="..." align="center" valign="top"><A HREF="(.*?)" class="opacityit"><IMG SRC="(.*?)" width="160" height="98" BORDER=0 ALT="(.*?)" title="', data)
        print content
        if content:
            for each in content:
                url, img, title = each
                title = unicode(title, 'windows-1256')
                title = str(title)
                url = str(url)
                print url
                img = str(img)
                title = '%s' % title
                self.content_list.append(show_(title, url, img))

        else:
            self.content_list = []
            self.check = 'series'
            content = re.findall('<div style="width: 200px; height: 98px;float: right; text-align:center;cursor: pointer;" ><A HREF="(.*?)" class="opacityit"><IMG SRC="(.*?)" WIDTH="160" HEIGHT="98" BORDER=0 title=".*?" ALT="(.*?)" onMouseOver="this\\.style\\.border = \'#333333 solid 1px\'" onMouseOut="this\\.style\\.border = \'#FFF0DC solid 1px\'"></A></div>', data)
            print content
            if content:
                for each in content:
                    url, img, title = each
                    title = str(title).decode('cp1256').encode('utf-8')
                    newtitle = str(title)
                    url = 'http://www.farfesh.com/%s' % url
                    print title
                    self.content_list.append(show_(newtitle, url, img))

            else:
                self.content_list = []
                content = re.findall('<A HREF="(.*?)"><IMG SRC="(.*?)" WIDTH="160" HEIGHT="98" BORDER=0 ALT="(.*?)" title=', data)
                print content
                if content:
                    for each in content:
                        url, img, title = each
                        title = str(title).decode('cp1256').encode('utf-8')
                        newtitle = str(title)
                        url = 'http://www.farfesh.com/%s' % url
                        print url
                        self.content_list.append(show_(newtitle, url, img))

                else:
                    self.content_list = []
                    content = re.findall('"><img src="(.*?)" border=0>&nbsp;<a href="(.*?)" class="Link5">(.*?)</a></div></div>', data)
                    print content
                    for each in content:
                        img, url, title = each
                        img = img.replace('gif', 'jpg')
                        title = str(title).decode('cp1256').encode('utf-8')
                        newtitle = str(title)
                        print url
                        self.content_list.append(show_(newtitle, url, img))

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

    def list_series(self, data, name):
        self.check = 'series1'
        self.series_list = []
        series = re.findall('<A HREF="(.*?)" class="opacityit"><IMG SRC="(.*?)" title="(.*?)" title=', data)
        if series:
            for each in series:
                url, img, title = each
                title = str(title).decode('cp1256').encode('utf-8')
                print title
                title = title.replace(' ', '')
                newtitle = str(title)
                print newtitle
                self.series_list.append(show_(newtitle, url, img))

        else:
            series = re.findall('<TD width="190" align="center" valign="top"><A HREF="(.*?)" class="opacityit"><IMG SRC="(.*?)" title="(.*?)" alt', data)
            if series:
                for each in series:
                    url, img, title = each
                    title = str(title).decode('cp1256').encode('utf-8')
                    print title
                    title = title.replace(' ', '')
                    newtitle = str(title)
                    print newtitle
                    self.series_list.append(show_(newtitle, url, img))

            else:
                series = re.findall('<A HREF="(.*?)"><IMG SRC="(.*?)".*?ALT=".*?" title="(.*?)"', data)
                if series:
                    for each in series:
                        url, img, title = each
                        title = str(title).decode('cp1256').encode('utf-8')
                        newtitle = str(title)
                        print newtitle
                        self.series_list.append(show_(newtitle, url, img))

        self['menulist'].l.setList(self.series_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        try:
            self.load_poster()
        except:
            print 'error loading cover'

    def list_series1(self, data, name):
        self.check = 'series2'
        self.series1_list = []
        series = re.findall('<TD width="190" align="center" valign="top"><A HREF="(.*?)" class="opacityit"><IMG SRC="(.*?)" title="(.*?)" alt', data)
        print series
        if series:
            for each in series:
                url, img, title = each
                title = str(title).decode('cp1256').encode('utf-8')
                print title
                title = title.replace(' ', '')
                newtitle = str(title)
                print newtitle
                self.series1_list.append(show_(newtitle, url, img))

        else:
            series = re.findall('<A HREF="(.*?)" class="opacityit"><IMG SRC="(.*?)" width="..." height=".." BORDER=0 ALT=".*?" title="(.*?)"', data)
            if series:
                for each in series:
                    url, img, title = each
                    title = str(title).decode('cp1256').encode('utf-8')
                    print title
                    title = title.replace(' ', '')
                    newtitle = str(title)
                    print newtitle
                    self.series_list.append(show_(newtitle, url, img))

            else:
                series = re.findall('<A HREF="(.*?)"><IMG SRC="(.*?)".*?ALT=".*?" title="(.*?)"', data)
                if series:
                    for each in series:
                        url, img, title = each
                        title = str(title).decode('cp1256').encode('utf-8')
                        newtitle = str(title)
                        print newtitle
                        self.series_list.append(show_(newtitle, url, img))

        self['menulist'].l.setList(self.series1_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        try:
            self.load_poster()
        except:
            print 'error loading cover'

    def get_player_url(self, data, name):
        print 'i am here'#<link rel="video_src" href="http://www.farfesh.com/u/videoplayer/player.php?mediaID=5232"/>
#<link rel="video_src" href="http://50.7.168.186:8081/vod6/oredo-rajolan-59.mp4"/>

        link = re.findall('frameborder="0" src="(.*?)" allowfullscreen></iframe>', data)
        if link:
            req = urllib2.Request(link[0])
            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
            final_url = re.findall('hls: \'(.*?)\'', response)
            #final_url = str(final_url[0]).replace('%3A', ':').replace('%2F', '/')
            if final_url:
                link=final_url[0]              
                self.play_that_shit(link, name)
            #else:
            #    link='http://127.0.0.1:88/'+link[0]+'.mp4 headers={"Range":"bytes=0-","Referer":"http://www.farfesh.com/View.asp?ID=86325&Chosen_ID=&ZoneID=1266"}'#
#
#                self.play_that_shit(link, name)
        else:
            lnk=re.findall('(http://origin.riktak.com:8081/.*?mp4)\'',data)
            print lnk
            self.play_that_shit(lnk[0], name)

    def play_that_shit(self, data, name):
        sref = eServiceReference(4097, 0, data)
        sref.setName(name)
        self.session.open(MoviePlayer, sref)

    def exit(self):
        print self.check
        if self.check == 'abc':
            self.close()
        elif self.check == 'list_content':
            self.check = 'abc'
            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        elif self.check == 'listcontent':
            self.check = 'abc'
            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        elif self.check == 'series1':
            self.check = 'series'
            self['menulist'].l.setList(self.content_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        elif self.check == 'series':
            self.check = 'abc'
            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/farfesh_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/farfesh/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 '[farfesh] 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 '[farfesh] 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 '[farfesh] 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/farfesh/'):
            os.system('mkdir /tmp/farfesh/')
        else:
            print '[farfesh] /tmp/farfesh/ allready present'