from imports import *
import StringIO

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, type):
    res = [(name,
      link,
      image,
      type)]
    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 show_news(news):
    res = [news]
    res.append(MultiContentEntryText(pos=(0, 0), size=(40, 40), font=4, text=news, flags=RT_HALIGN_RIGHT))
    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 bokra(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,
         '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(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('bokra')
        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)
        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 = []
        url = 'http://shahidlive.com/'
        getPage(url, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_cat)

    def get_cat(self, data):
        target = re.findall(' <ul class="hidden-xs">(.*?)\\s(.*?) </ul>', data, re.DOTALL)
        mylist = [ items for i in target for items in i if items != '' ]
        final_catergories = [ it for itr in mylist for it in itr.split('/a></li>') if '="' in str(it) ]
        for itr in final_catergories:
            my_data = itr.split('="')[1]
            path = 'http://shahidlive.com' + my_data.split('">')[0]
            title = my_data.split('">')[1]
            title = title.replace('<', '')
            self.cat_list.append(cat_(title, path))

        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)

    def list_shows(self, path):
        self.info = 'list_shows'
        self.show_list = []
        getPage(path, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_it, path)

    def list_it(self, data, path):
        pages_list = []
        pages = re.findall('<a class="page" href="(.*?)">.</a>', data, re.DOTALL)
        print 'Data : \n' + str(pages)
        for each in pages:
            url = each
            url = 'http://shahidlive.com' + url
            getPage(url, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_it1)

    def list_it1(self, data):
        target = re.findall('<div class="col-md-3(.*?)\\s(.*?)</h4></div>', data, re.DOTALL)
        for itr in target:
            for item in itr[1:]:
                item = item.split('">')
                path = 'http://shahidlive.com' + item[1].replace('<a href="', '').strip()
                img = item[3].split('="')[1].split('"')[0].strip()
                if 'jpg' in img:
                    img=img
                else:
                    img = item[2].split('="')[1].split('"')[0].strip()
                print item
                print img
                if '<div class="play small' in item[4]:
                    title = item[6].replace('<h4>', '').strip()
                    type = '2'
                else:
                    title = item[4].replace('<h4>', '').strip()
                    type = '1'
                if 'no-image.jpg' in img:
                    img = 'http://shahidlive.com' + str(img)
                else:
                    img = str(img)
                self.show_list.append(show_(title, path, img, type))

        self['menulist'].l.setList(self.show_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_episodes(self, url):
        self.info = 'list_episodes'
        self.episodes_list = []
        getPage(url, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_episodes1, url)

    def list_episodes1(self, data, url):
        pages = re.findall('<a class="page" href="(.*?)">.</a>', data, re.DOTALL)
        print 'Data : \n' + str(pages)
        for each in pages:
            url = each
            url = 'http://shahidlive.com' + url
            getPage(url, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_episodes2)

    def list_episodes2(self, data):
        target = re.findall('<div class="col-md-3(.*?)\\s(.*?)</h4></div>', data, re.DOTALL)
        for itr in target:
            for item in itr[1:]:
                item = item.split('">')
                path = 'http://shahidlive.com' + item[1].replace('<a href="', '').strip()
                img = item[2].split('="')[1].split('"')[0].strip()
                print item
                if '<div class="play small' in item[4]:
                    title = item[6].replace('<h4>', '').strip()
                    type = '2'
                else:
                    title = item[4].replace('<h4>', '').strip()
                    type = '1'
                if 'no-image.jpg' in img:
                    img = 'http://shahidlive.com' + str(img)
                else:
                    img = str(img)
                self.episodes_list.append(show_(title, path, img, type))

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

    def get_play_link(self, url):
        print url
        url = 'http://shahidlive.com/Play/' + url.split('Video-')[1] + '-681-382'
        #url='http://play.bokracdn.com/?ID=' + url.split('Video-')[1] +'&width=799&height=448.88&iphoneApp=true'
        print url
        getPage(url, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.read_link, url)

    def read_link(self, data, url):
        #target = re.findall('<iframe src="(.*?)"', data, re.DOTALL)
        target=re.findall('<iframe src="(http://play.*?)"',data)
        #print target
        if target:
            target = target[0]
            target = target.replace(' ', '')
            print target
#            if target:
#               self.play_movie(target)
            getPage(target, timeout=8, method='GET', headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.read_link1, target)
        else:
            print 'i am here'
            target = re.findall('<iframe src="(.*?)"', data, re.DOTALL)
            getPage(target[0], timeout=8, method='GET', headers={'Host':'play.bokracdn.com','Upgrade-Insecure-Requests':'1','User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}).addCallback(self.read_link1, target)

    def read_link1(self, data, url):
        print data
        link_file = re.findall('<source src="(.*?)" preload="none" type=\'video/mp4\'',data)
        if link_file:
            self.play_movie(link_file[0])

    def play_movie(self, link):
        if link:
            sref = eServiceReference(4097, 0, link)
            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]
            type = self['menulist'].getCurrent()[0][3]
            print selectedEntry
            url = str(selectedEntry)
            if type == '1':
                self.get_play_link(url)
            else:
                self.list_episodes(url)
        elif self.info == 'list_episodes':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            self.get_play_link(url)

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            if fileExists('/tmp/Albatros/poster.jpg'):
                os.system('rm -r /tmp/Albatros/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/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 = '/usr/lib/enigma2/python/Plugins/Extensions/shahidSeries/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 '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 'no cover.. error'
        return

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