from imports import *
from about import *
import requests
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 livetvhd(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('LiveTVHD')
        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):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def right(self):
        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=[('https://livetvhd.net/api/videos/category/sportives','sportives'),
        ('https://livetvhd.net/api/videos/category/musicales','musicales'),
        ('https://livetvhd.net/api/videos/category/generalistes','generalistes'),
        ('https://livetvhd.net/api/videos/category/internationales','internationales'),
        ('https://livetvhd.net/api/videos/category/cinema','cinema'),
        ('https://livetvhd.net/api/videos/category/documentaires','documentaires'),
        ('https://livetvhd.net/api/videos/category/jeunesse','jeunesse'),
        ('https://livetvhd.net/api/videos/category/drama','drama'),
        ('https://livetvhd.net/api/videos/category/news','news'),
        ('https://livetvhd.net/api/videos/category/religieuses','religieuses')]
        for url,title in cat:
            self.cat_list.append(show_(title, url, None,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)
        return

    def list_channels(self,data):
        self.info = 'list_channels'
        self.show_list = []
        self.ch_list = []
        selected = self['menulist'].getCurrent()[0][0]
        data=re.findall('"title": "(.*?)".*?"slug": "(.*?)".*?"url": ".*?".*?"thumbnail": "(.*?)"',data,re.DOTALL)
        for title,slug,thumb in data:
            title=str(title.replace(' Live streaming en direct',''))
            thumb=str(thumb.replace('\\',''))
            url='https://livetvhd.net/api/video/'+str(slug)
            self.show_list.append(show_(title,url,thumb,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'
        link=re.findall('"url": "(.*?)",',link)
        if link:
            if 'cdn' in link[0]:		
                link='http://127.0.0.1:88/hls://'+str(link[0].replace('\\','')) +' headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36","Origin":"https://livetvhd.net","Referer":"https://livetvhd.net/video/internationales/tf1-live-streaming-en-direct","X-Requested-With":"ShockwaveFlash/24.0.0.221"}'
                print link
            else:
                link='http://127.0.0.1:88/hlsvariant://'+str(link[0].replace('\\','')) +' headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36","Origin":"https://livetvhd.net","Referer":"https://livetvhd.net/video/internationales/tf1-live-streaming-en-direct","X-Requested-With":"ShockwaveFlash/24.0.0.221"}'
                print link			
            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]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        selectedIndex= self['menulist'].l.getCurrentSelection()[0][3]
        if self.info == 'list_cat':
            url=selectedEntry
            r=requests.get(url, headers={'referer':'https://livetvhd.net/video/news','user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'})
            self.list_channels(r.text)
        elif self.info=='list_channels':
            url = str(selectedEntry)
            r=requests.get(url, headers={'referer':'https://livetvhd.net/video/news','user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'})
            self.play_movie(r.text)
           

    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)