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

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, index):
    res = [(name,
      link,
      image,
      index)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, 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 ecanlitvizle(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('Ecanalitvizle')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.dir()
        self.info = ''
        self.video_list = []
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.show_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 == 'videos':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'videos':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'videos':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'videos':
            try:
                self.load_poster()
                info = self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def show_cat(self):
        self.info = 'cat'
        self.cat = []
        self.cat_list = [('http://www.ecanlitvizle.net/category/haber-tv-kanallari/', 'Haber'),
         ('http://www.ecanlitvizle.net/category/spor-tv-kanallari/', 'Spor'),
         ('http://www.ecanlitvizle.net/category/cocuk-tv-kanallari/', '\xc3\x87ocuk'),
         ('http://www.ecanlitvizle.net/category/muzik-tv-kanallari/', 'M\xc3\xbczik'),
         ('http://www.ecanlitvizle.net/category/dini-tv-kanallari/', 'Dini'),
         ('http://www.ecanlitvizle.net/category/yerel-tv-kanallari/', 'Yerel'),
         ('http://www.ecanlitvizle.net/category/sinema-tv-kanallari/', 'Sinema'),
         ('http://www.ecanlitvizle.net/category/yabanci-tv-kanallari/', 'Yabanc\xc4\xb1')]
        for url, title in self.cat_list:
            self.cat.append(cat_(title, url))

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

    def get_videos(self, data):
        self.video_list = []
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        self.info = 'videos'
        #max_nr = 2
        #i = 1
        url = str(selectedEntry)
        #for i in range(1, max_nr):
        #    url = url + 'page/' + str(i) + '/'
        #    print url
        getPage(url, timeout=8, cookies=cj, 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',
        'Host': 'www.ecanlitvizle.net'}).addCallback(self.get_videos1)
        #    i += 1
        #    url = str(selectedEntry)

    def get_videos1(self, data):
        print data
        videos = re.findall('<a href="(.*?)" title="(.*?)">.*?<div class="kanallarlogo"><img src="(.*?)" alt=".*?" width="..."/></div>', data, re.DOTALL)
        if videos:
            for url, title, img in videos:
                if 'E Canl\xc4\xb1 Tv \xc4\xb0zle' not in title:
                    self.video_list.append(show_(title, url, img, None))

            self['menulist'].l.setList(self.video_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            info = self['menulist'].getCurrent()[0][3]
            self['text'].setText(info)
        return

    def get_link(self, data):
        link = re.findall('file: "(.*?)",', data, re.DOTALL)
        print link
        if link:
            self.play_vid(link[0])
        else:#<p><iframe src="http://www.ecanlitvizle.net/embed.php?kanal=trt-spor-izle" frameborder="0" height="100%" scrolling="no" width="100%" allowfullscreen></iframe></p>
            iframe = re.findall('<iframe src="(.*?)" frameborder="0" height=', data)
            url = iframe[0]
            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',
             'Host': 'www.ecanlitvizle.net',
             'Referer': 'http://www.ecanlitvizle.net/'}).addCallback(self.get_link1)

    def get_link1(self, data):
        print data
        link = re.findall("file: '(.*?)',", data)
        print link
        if link:
            self.play_vid(link[0])
        else:
            link = re.findall('file:"(.*?)"\\}', data)
            print link
            if link:
                self.play_vid(link[0])
            else:
                link = re.findall('file.*?"(.*?)",', data)
                print link
                if link:
                    self.play_vid(link[0])

    def play_vid(self, data):
        self.info = 'player'
        if data:
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            sref = eServiceReference(4097, 0, data)
            sref.setName(selectedName)
            self.session.nav.playService(sref)
            self.hide()

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        if self.info == 'cat':
            url = str(selectedEntry)
            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',
             'Referer': 'http://flash-moviez.ucoz.org/publ/alle_moviez/action/3'}).addCallback(self.get_videos)
        elif self.info == 'videos':
            url = str(selectedEntry)
            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_link)

    def exit(self):
        print self.info
        if self.info == 'cat':
            self.close()
        elif self.info == 'videos':
            self.info = 'cat'
            self['menulist'].l.setList(self.cat)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info = 'videos'
            self['menulist'].l.setList(self.video_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()

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

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