from imports import *
from about import *
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


class moreiptv(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}, -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('IPTVFree')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        global old_ref
        old_ref=self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.list_cat)

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

    def up(self):
        if self.info == 'list_cat':
            self[self.currentList].up()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            self.load_poster()
        else:
            self[self.currentList].up()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
			
    def down(self):
        if self.info == 'list_cat':
            self[self.currentList].down()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
            self.load_poster()
        else:
            self[self.currentList].down()
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)

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

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

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        cat=[('USA Channels','http://flaglane.com/download/american-flag/american-flag-graphic.png'),('Spain Channels','http://flaglane.com/download/spanish-flag/spanish-flag-graphic.png'),('Frensh Channels','http://flaglane.com/download/french-flag/french-flag-graphic.png'),('UK Channels','http://flaglane.com/download/british-flag/british-flag-graphic.png'),('Portugues Channels','http://flaglane.com/download/portuguese-flag/portuguese-flag-graphic.png'),('German Channels','http://flaglane.com/download/german-flag/german-flag-graphic.png'),('Italian Channels','http://flaglane.com/download/italian-flag/italian-flag-graphic.png'),('Arabic Channels','http://flaglane.com/download/emirian-flag/emirian-flag-graphic.png'),('Turkey Channels','http://flaglane.com/download/turkish-flag/turkish-flag-graphic.png'),('Netherland Channels','http://flaglane.com/download/dutch-flag/dutch-flag-graphic.png'),('Albanian Channels','http://flaglane.com/download/albanian-flag/albanian-flag-graphic.png'),('Indian Channels','https://www.lyngsat-logo.com/logo/flag/az/in.png')]
        for (category,img) in cat:
            self.cat_list.append(show_(category, None, img,None))
        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()
        return

    def list_channels(self,data):
        self.info = 'list_channels'
        self.show_list = []
        self.ch_list = []##EXTINF:-1 group-title="S-1-globiptv", 13th Street HD (s-1)
        selected = self['menulist'].getCurrent()[0][0]##EXTINF:-1 group-title="SERVER 1", Anixe HD Series (hls)(server 1)
##EXTINF:-1 group-title="SERVER 1-IPTV-VOLKAN" tvg-logo="http://exabytetv.info/img/icon.png", ARTE   (s-1)
#http://IPTV-VOLKAN.NET:8000/live/raja/cLRD6FYE7R/485.m3u8
        ch=re.findall('#EXTINF:-1 group-title="S.*?" tvg-logo=".*?", (.*?)\n(http.*?)\n',data)
        if ch:
            for each in ch:
                title,url=each
                url=url
                self.show_list.append(show_(title, url, None,None))
        else:
            self.show_list.append(show_('Sorry no channels available','http://',None,None))
        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)
		
    def play_movie(self, link):
        self.info='player'
        if link:
            if 'ts' in link:
                link='http://127.0.0.1:88/httpstream://'+link+' headers={"User-Agent":"VLC/2.2.1 LibVLC/2.2.1"}'
                selectedName = self['menulist'].l.getCurrentSelection()[0][0]
                sref = eServiceReference(4097, 0, link)
                sref.setName(selectedName)
                self.session.nav.playService(sref)
                self.hide()
            else:
                link='http://127.0.0.1:88/hls://'+link+' headers={"User-Agent":"VLC/2.1.5 LibVLC/2.1.5"}'
                selectedName = self['menulist'].l.getCurrentSelection()[0][0]
                sref = eServiceReference(4097, 0, link)
                sref.setName(selectedName)
                self.session.nav.playService(sref)
                self.hide()

    def ok(self):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        sel = self['menulist'].l.getCurrentSelection()[0][0]
        if self.info == 'list_cat':
            if sel=='USA Channels':
                url='http://www.exabytetv.info/USA.m3u'
            elif sel=='Spain Channels':
                url='http://www.exabytetv.info/ESP.m3u'
            elif sel=='Frensh Channels':
                url='http://www.exabytetv.info/FRA.m3u'
            elif sel=='UK Channels':
                url='http://www.exabytetv.info/UK.m3u'
            elif sel=='Portugues Channel':
                url='http://www.exabytetv.info/PRT.m3u'
            elif sel=='German Channels':
                url='http://www.exabytetv.info/DEU.m3u'
            elif sel=='Italian Channels':
                url='http://www.exabytetv.info/ITA.m3u'
            elif sel=='Arabic Channels':
                url='http://www.exabytetv.info/SAU.m3u'
            elif sel=='Turkey Channels':
                url='http://www.exabytetv.info/TUR.m3u'
            elif sel=='Netherland Channels':
                url='http://www.exabytetv.info/NLD.m3u'
            elif sel=='Albanian Channels':
                url='http://www.exabytetv.info/ALB.m3u'
            elif sel=='Indian Channels':
                url='http://www.exabytetv.info/IND.m3u'
            try:
                req = urllib2.Request(url)
                req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')
                resp = urllib2.urlopen(req)
                body = resp.read()
                print body
                self.list_channels(body)
            except:
                print 'failed to login'
        elif self.info=='list_channels':
            url = str(selectedEntry)
            self.play_movie(url)

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            self.close(self.session, 'exit')
        elif self.info == 'list_channels':
            self.list_cat()
        elif self.info=='player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info='list_channels'
            self['menulist'].l.setList(self.show_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/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/Albatros/'):
            os.system('mkdir /tmp/Albatros/')
        else:
            print '/tmp/Albatros/ allready present'