from imports import *
from Tools.Directories import fileExists, pathExists
UserAgent = 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'

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 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 liveonlinetv(Screen):

    def __init__(self, session):
        global old_ref
        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['title'] = Label('LiveOnlineTV')
        self['text'] = Label('')
        self['poster'] = Pixmap()
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        self.index = ''
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.abc)

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

    def up(self):
        self[self.currentList].up()

    def down(self):
        self[self.currentList].down()

    def left(self):
        self[self.currentList].pageUp()

    def right(self):
        self[self.currentList].pageDown()

    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 abc(self):
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_list = []
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.genre_name = 'sports'
        self.load_data_channels()

    def load_data_channels(self):
        matches = [
        ('Bein Sports News','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=beinsportsnews-hq'),
        ('Bein Sports 1','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein1-hq'),
        ('Bein Sports 2','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein2-hq'),
        ('Bein Sports 3','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein3-hq'),
        ('Bein Sports 4','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein4-hq'),
        ('Bein Sports 5','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein5-hq'),
        ('Bein Sports 6','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein6-hq'),
        ('Bein Sports 7','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein7-hq'),
        ('Bein Sports 8','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein8-hq'),
        ('Bein Sports 9','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein9-hq'),
        ('Bein Sports 10','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein10-hq'),
        ('Bein Sports 11','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein11-hq'),
        ('Bein Sports 12','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein12-hq'),
        ('Bein Sports 13','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein13-hq'),
        ('Bein Sports 1 FR','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein1fr-hq'),
        ('Bein Sports 2 FR','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein2fr-hq'),
        ('Bein Sports 3 FR','http://m.liveonlinetv247.info/external.php?title=beIN%20Sports&stream=bein3fr-hq'),
        ('Sport TV 1','http://m.liveonlinetv247.info/external.php?title=Sport%20TV&stream=sporttv1-hq'),
        ('Sport TV 2','http://m.liveonlinetv247.info/external.php?title=Sport%20TV&stream=sporttv2-hq'),
        ('Sport TV 3','http://m.liveonlinetv247.info/external.php?title=Sport%20TV&stream=sporttv3-hq'),
        ('Sport TV 4','http://m.liveonlinetv247.info/external.php?title=Sport%20TV&stream=sporttv4-hq'),
        ('Sport TV 5','http://m.liveonlinetv247.info/external.php?title=Sport%20TV&stream=sporttv5-hq'),
        ('SkySports 1','http://m.liveonlinetv247.info/external.php?title=Sky%20Sports&stream=skysports1-hq'),
        ('SkySports 2','http://m.liveonlinetv247.info/external.php?title=Sky%20Sports&stream=skysports2-hq'),
        ('SkySports 3','http://m.liveonlinetv247.info/external.php?title=Sky%20Sports&stream=skysports3-hq'),
        ('SkySports 4','http://m.liveonlinetv247.info/external.php?title=Sky%20Sports&stream=skysports4-hq'),
        ('SkySports 5','http://m.liveonlinetv247.info/external.php?title=Sky%20Sports&stream=skysports5-hq'),
        ('SkySports F1','http://m.liveonlinetv247.info/external.php?title=Sky%20Sports&stream=skysportsf1-hq'),
        ('SkySports News','http://m.liveonlinetv247.info/external.php?title=Sky%20Sports&stream=skysportsnews-hq'),
        ('SkySports BoxOfice','http://m.liveonlinetv247.info/external.php?title=Sky%20Sports&stream=skysportsboxoffice-hq'),
        ('SkySport 1 Italy','http://m.liveonlinetv247.info/external.php?title=Sky%20Sport%20Italia&stream=skysport1italia-hq'),
        ('SkySport 2 Italy','http://m.liveonlinetv247.info/external.php?title=Sky%20Sport%20Italia&stream=skysport2italia-hq'),
        ('SkySport 3 Italy','http://m.liveonlinetv247.info/external.php?title=Sky%20Sport%20Italia&stream=skysport3italia-hq'),
        ('SkySport 24 Italy','http://m.liveonlinetv247.info/external.php?title=Sky%20Sport%20Italia&stream=skysport24italia-hq'),
        ('SkyCalcio Italy','http://m.liveonlinetv247.info/external.php?title=Sky%20Sport%20Italia&stream=skycalcio-hq'),
        ('SkySport MotoGP Italy','http://m.liveonlinetv247.info/external.php?title=Sky%20Sport%20Italia&stream=skysportmotogp-hq'),
        ('BT Sport 1','http://m.liveonlinetv247.info/external.php?title=BT%20Sport&stream=btsport1-hq'),
        ('BT Sport 2','http://m.liveonlinetv247.info/external.php?title=BT%20Sport&stream=btsport2-hq'),
        ('BT Sport Europe','http://m.liveonlinetv247.info/external.php?title=BT%20Sport&stream=btsporteurope-hq'),
        ('BT Sport ESPN','http://m.liveonlinetv247.info/external.php?title=BT%20Sport&stream=espnuk-hq'),
        ('ESPN UK','http://m.liveonlinetv247.info/external.php?title=ESPN&stream=espnuk-hq'),
        ('ESPN USA','http://m.liveonlinetv247.info/external.php?title=ESPN&stream=espnusa-hq'),
        ('Canal + Football','http://m.liveonlinetv247.info/external.php?title=Canal+%20F%C3%BAtbol&stream=canalfutbol-hq'),
        ('Canal + Liga','http://m.liveonlinetv247.info/external.php?title=Canal+%20Liga&stream=canalliga-hq'),
        ('Canal+ Sport','http://m.liveonlinetv247.info/external.php?title=Canal+%20Sport&stream=canalsport-hq'),
        ('Eurosport 1','http://m.liveonlinetv247.info/external.php?title=Eurosport&stream=eurosport-hq'),
        ('Eurosport 2','http://m.liveonlinetv247.info/external.php?title=Eurosport&stream=eurosport2-hq'),
        ('WWE Network','http://m.liveonlinetv247.info/external.php?title=WWE%20Network&stream=wwe-hq'),
        ('Sony Six','http://m.liveonlinetv247.info/external.php?title=Sony%20SIX&stream=sonysix-hq'),
        ('Star Sports 3','http://m.liveonlinetv247.info/external.php?title=Star%20Sports%203&stream=starsports3-hq'),
        ('TenSports 1','http://m.liveonlinetv247.info/external.php?title=TEN%201&stream=ten1-hq'),
        ('PTV Sports','http://m.liveonlinetv247.info/external.php?title=PTV%20Sports&stream=ptvsports-hq'),
        ('Premier Sports','http://m.liveonlinetv247.info/external.php?title=Premier%20Sports&stream=premiersports-hq'),
        ('BoxNation','http://m.liveonlinetv247.info/external.php?title=BoxNation&stream=boxnation-hq'),
        ('WillowTV','http://m.liveonlinetv247.info/external.php?title=Willow%20TV&stream=willow-hq'),
        ('Setanta Sports','http://m.liveonlinetv247.info/external.php?title=Setanta%20Sports&stream=setantasports-hq'),
        ('Fox Sports 1','http://m.liveonlinetv247.info/external.php?title=Fox%20Sports&stream=foxsports1-hq'),
        ('Fox Sports 2','http://m.liveonlinetv247.info/external.php?title=Fox%20Sports&stream=foxsports2-hq'),
        ('TSN','http://m.liveonlinetv247.info/external.php?title=TSN&stream=tsn-hq'),
        ('TSN 2','http://m.liveonlinetv247.info/external.php?title=TSN&stream=tsn2-hq'),
        ('NBA TV','http://m.liveonlinetv247.info/external.php?title=NBA%20TV&stream=nbatv-hq'),
        ('NFL Network','http://m.liveonlinetv247.info/external.php?title=NFL%20Network&stream=nflnetwork-hq'),
        ('Racing UK','http://m.liveonlinetv247.info/external.php?title=Racing%20UK&stream=racinguk-hq'),
        ('At The Races','http://m.liveonlinetv247.info/external.php?title=At%20The%20Races&stream=attheraces-hq'),
        ('Motors TV','http://m.liveonlinetv247.info/external.php?title=Motors%20TV&stream=motorstv-hq'),
        ('LFCTV','http://m.liveonlinetv247.info/external.php?title=LFCTV&stream=lfctv-hq'),
        ('MUTV','http://m.liveonlinetv247.info/external.php?title=MUTV&stream=mutv-hq'),
        ('ChelseaTV','http://m.liveonlinetv247.info/external.php?title=Chelsea%20TV&stream=chelseatv-hq'),
        ('Golf Channel','http://m.liveonlinetv247.info/external.php?title=Golf%20Channel&stream=golfchannel-hq'),
        ('NBCSN','http://m.liveonlinetv247.info/external.php?title=NBCSN&stream=nbcsn-hq'),
        ('Sportsnet World','http://m.liveonlinetv247.info/external.php?title=Sportsnet&stream=snwl-hq'),
        ('Sportsnet One','http://m.liveonlinetv247.info/external.php?title=Sportsnet&stream=snone-hq'),
        ('Sportsnet Ontario','http://m.liveonlinetv247.info/external.php?title=Sportsnet&stream=snontario-hq')]
        for title, url in matches:
            self.letter_list.append(cat_(title, url))

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

    def ok(self):
        if self.check == 'abc':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            self.loading_ok = False
            uri = selectedEntry
            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.play_that_shit)

    def play_that_shit(self, data):
        self.index = 'player'
        hls = re.findall('<source src="(.*?)" type=', data)
        if hls:
            print hls
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            playlink = 'http://127.0.0.1:88/hlsvariant://' + hls[0]
            sref = eServiceReference(4097, 0, playlink)
            sref.setName(selectedName)
            self.session.nav.playService(sref)
            self.hide()
        else:
            hls = re.findall('<a href="(http://live1.greenlie.org.*?)">', data)
            if hls:
                selectedName = self['menulist'].l.getCurrentSelection()[0][0]
                sref = eServiceReference(4097, 0, hls[0])
                sref.setName(selectedName)
                self.session.nav.playService(sref)
                self.hide()

    def exit(self):
        if self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'nothing'
        else:
            self.close()

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

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


def main(session, **kwargs):
    session.open(streamking)


def Plugins(path, **kwargs):
    global plugin_path
    plugin_path = path
    return [PluginDescriptor(name='Teledunet', description='Teledunet Streamer', where=[PluginDescriptor.WHERE_PLUGINMENU], fnc=main, icon='plugin.png')]