from setup import *
from about import *
from imports import *
fav_file='/usr/lib/enigma2/python/Plugins/Extensions/Albatros/fav_streamcloud'

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, img):
    res = [(name, link, img)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


def cat_(name, link):
    res = [(name, link)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class castfree(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,
         'red': self.exit,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('Castfree.me')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label(' ')
        self['yellow'] = Label(_('About'))
        self['blue'] = Label(' ')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.dir()
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.get_list)
		
    def get_list(self):
        self.index = 'list_series'
        self.series_list = []
        cast_free_list=[('*************************  INGLATERRA *****************************','http://','http://'),
        ('Box Nation','http://castfree.me/ace/uk/attheraces.php','http://'),
        ('EUROSPORT 1 HD','http://castfree.me/ace/uk/eurosport1hd.php','http://'),
        ('EUROSPORT 2 HD','http://castfree.me/ace/uk/eurosport2hd.php','http://'),
        ('AT THE RACES','http://castfree.me/ace/uk/attheraces.php','http://'),
        ('PREMIER SPORTS HD','http://castfree.me/ace/uk/premier.php','http://'),
        ('BT SPORT 1 HD','http://castfree.me/ace/uk/btsports1.php','http://'),
        ('BT SPORT 2 HD','http://castfree.me/ace/uk/btsports2.php','http://'),
        ('BT SPORT EXTRA HD','http://castfree.me/ace/uk/btextra.php','http://'),
        ('BT EUROPA','http://castfree.me/ace/uk/bteurope.php','http://'),
        ('ESPN 1HD','http://castfree.me/ace/uk/espnuk.php','http://'),
        ('SKY SPORTS 1 HD','http://castfree.me/ace/uk/skysports1uk.php','http://'),
        ('SKY SPORTS 2 HD','http://castfree.me/ace/uk/skysports2uk.php','http://'),
        ('SKY SPORTS 3 HD','http://castfree.me/ace/uk/skysports3uk.php','http://'),
        ('SKY SPORTS 4 HD','http://castfree.me/ace/uk/skysports4uk.php','http://'),
        ('SKY SPORTS 5 HD','http://castfree.me/ace/uk/skysports5uk.php','http://'),
        ('SKY F1 HD','http://castfree.me/ace/uk/skysportsf1uk.php','http://'),
        ('*********************** USA *********************','http://','http://'),
        ('WWE RAW HD','http://castfree.me/ace/us/wwe.php','http://'),
        ('TSN 1 HD','http://castfree.me/ace/us/tsn1.php','http://'),
        ('TSN 2 HD','http://castfree.me/ace/us/tsn2.php','http://'),
        ('TSN 3 HD','http://castfree.me/ace/us/tsn3.php','http://'),
        ('TSN 4 HD','http://castfree.me/ace/us/tsn4.php','http://'),
        ('TSN 5 HD','http://castfree.me/ace/us/tsn5.php','http://'),
        ('*****************************  ALEMANIA **********************','http://','http://'),
        ('Sky Sport 1 HD','http://castfree.me/ace/de/SkySport1.php','http://'),
        ('Sky Sport 2 HD','http://castfree.me/ace/de/SkySport2.php','http://'),
        ('Sky BUNDESLIGA 1 HD','http://castfree.me/ace/de/skybundesliga1.php','http://'),
        ('SPORT 1 HD','http://castfree.me/ace/de/sport1.php','http://'),
        ('SPORT 1+ HD','http://castfree.me/ace/de/sport1+.php','http://'),
        ('*************************  POLONIA  ****************************','http://','http://'),
        ('TVN24','http://castfree.me/ace/pol/tvn24.php','http://'),
        ('TVP 1','http://castfree.me/ace/pol/tvp1.php','http://'),
        ('TVP 2 HD','http://castfree.me/ace/pol/tvp2.php','http://'),
        ('TVP SPORT HD','http://castfree.me/ace/pol/tvpsport.php','http://'),
        ('POLSAT','http://castfree.me/ace/pol/polsat.php','http://'),
        ('POLSAT NEWS','http://castfree.me/ace/pol/polsatnews.php','http://'),
        ('POLSAT SPORTS HD','http://castfree.me/ace/pol/polsatsport.php','http://'),
        ('POLSAT SPORTS EXTRA','http://castfree.me/ace/pol/polsatextra.php','http://'),
        ('EUROSPORT 1','http://castfree.me/ace/pol/eurosport1.php','http://'),
        ('NSPORT+','http://castfree.me/ace/pol/nsport.php','http://'),
        ('ELEVEN','http://castfree.me/ace/pol/eleven1.php','http://'),
        ('ELEVEN SPORTS','http://castfree.me/ace/pol/eleven.php','http://'),
        ('CANAL+ SPORT HD','http://castfree.me/ace/pol/canal+sport.php','http://'),
        ('CANAL+ SPORT2 HD','http://castfree.me/ace/pol/canal+sport2.php','http://'),
        ('************************   HOLANDA  *******************************','http://','http://'),
        ('ZIGGO SELECT HD','http://castfree.me/ace/nl/selec.php','http://'),
        ('ZIGGO SPORT EXTRA  1','http://castfree.me/ace/nl/ziggo1.php','http://'),
        ('ZIGGO SPORT EXTRA  2','http://castfree.me/ace/nl/ziggo2.php','http://'),
        ('SPORT VOETBAL','http://castfree.me/ace/nl/voetball.php','http://'),
        ('FOX SPORTS 1','http://castfree.me/ace/nl/foxsport1.php','http://'),
        ('FOX SPORTS 2','http://castfree.me/ace/nl/foxsport2.php','http://'),
        ('FOX SPORTS 3','http://castfree.me/ace/nl/foxsport3.php','http://'),
        ('FOX SPORTS 4','http://castfree.me/ace/nl/foxsport4.php','http://'),
        ('FOX SPORTS 5','http://castfree.me/ace/nl/foxsport5.php','http://'),
        ('**********************  PORUGAL  ********************','http://','http://'),
        ('SPORTS TV 1 HD','http://castfree.me/ace/por/sporttv1.php','http://'),
        ('SPORTS TV 2 HD','http://castfree.me/ace/por/sporttv2.php','http://'),
        ('SPORTS TV 3 HD','http://castfree.me/ace/por/sporttv3.php','http://'),
        ('SPORTS TV 4 HD','http://castfree.me/ace/por/sporttv4.php','http://'),
        ('SPORTS TV 5 HD','http://castfree.me/ace/por/sporttv5.php','http://'),
        ('***************************  ESPANA *************************','http://','http://'),
        ('CANAL+FUTBOL','http://castfree.me/ace/es/canal+futbol.php','http://'),
        ('CANAL+DEPORTES','http://castfree.me/ace/es/canal+deporte.php','http://'),
        ('BEIN 1HD','http://castfree.me/ace/es/bein.php','http://'),
        ('MOVISTAR MOTO GP','http://castfree.me/ace/es/motogp.php','http://'),
        ('LA SEXTA','http://castfree.me/ace/es/sexta.php','http://'),
        ('CANAL BEIN LA LIGA','http://castfree.me/ace/es/liga.php','http://'),
        ('*******************   FRANCIA *********************','http://','http://'),
        ('SFR Sport 1','http://castfree.me/ace/fr/MaChaineSporthd1.php','http://'),
        ('SFR Sport 2','http://castfree.me/ace/fr/MaChaineSporthd2.php','http://'),
        ('CANAL+ Sport HD','http://castfree.me/ace/fr/canal+sport.php','http://'),
        ('BEIN 1HD','http://castfree.me/ace/fr/bein1.php','http://'),
        ('BEIN 2HD','http://castfree.me/ace/fr/bein2.php','http://'),
        ('BEIN 3HD','http://castfree.me/ace/fr/bein3.php','http://'),
        ('***************************   SUECIA *********************','http://','http://'),
        ('C MORE SPORT','http://castfree.me/ace/ar/cmoresport.php','http://'),
        ('**************************  RUMANIA **********************','http://','http://'),
        ('DIGI SPORT 1','http://castfree.me/ace/ar/digi1.php','http://'),
        ('DIGI SPORT 2','http://castfree.me/ace/ar/digi2.php','http://'),
        ('DIGI SPORT 3','http://castfree.me/ace/ar/digi3.php','http://'),
        ('DIGI SPORT 4','http://castfree.me/ace/ar/digi4.php','http://'),
        ('DIGI SPORT 5','http://castfree.me/ace/ar/digi5.php','http://'),
        ('DOLCE SPORT 1','http://castfree.me/ace/ar/dolce1.php','http://'),
        ('DOLCE SPORT 2','http://castfree.me/ace/ar/dolce2.php','http://'),
        ('********************  ARABE  ********************','http://','http://'),
        ('BEIN 1HD','http://castfree.me/ace/ar/bein1.php','http://'),
        ('BEIN 2HD','http://castfree.me/ace/ar/bein2.php','http://'),
        ('BEIN 3HD','http://castfree.me/ace/ar/bein3.php','http://'),
        ('********************  AUSTRIA  ********************','http://','http://'),
        ('Sky Sport Austria','http://castfree.me/ace/ar/SkySportAustria.php','http://'),
        ('********************  IRLANDA  ********************','http://','http://'),
        ('Setanta Sport Irland 1','http://castfree.me/ace/ar/SetantaSportIrland.php','http://'),
        ('********************  TURQUIA  ********************','http://','http://'),
        ('A Spor','http://castfree.me/ace/ar/asport.php','http://'),
        ('********************  SERVIA   EXU ********************','http://','http://'),
        ('Arena Sport 1','http://castfree.me/ace/ar/arena1.php','http://'),
        ('Arena Sport 2','http://castfree.me/ace/ar/arena2.php','http://'),
        ('Arena Sport 3','http://castfree.me/ace/ar/arena3.php','http://'),
        ('Arena Sport 4','http://castfree.me/ace/ar/arena4.php','http://'),
        ('Arena Sport 5','http://castfree.me/ace/ar/arena5.php','http://')]
        for title,url,img in cast_free_list:
            self.series_list.append(show_(title, url,img))
        self['menulist'].l.setList(self.series_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
		
    def about(self):
        self.session.open(AboutScreen)

    def up(self):
        self.cur_idx = int(self['menulist'].getSelectedIndex())
        comp = int(len(self.series_list))
        print 'list : ' + str(comp)
        print self.cur_idx
        if self.cur_idx == 0:
            print 'moving to last idx'
            self['menulist'].moveToIndex(comp - 1)
        else:
            self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        self.cur_idx = int(self['menulist'].getSelectedIndex())
        comp = int(len(self.series_list))
        if self.cur_idx == comp - 1:
            self['menulist'].moveToIndex(0)
        else:
            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 ok(self):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        print url
        if self.index == 'list_series':
            getPage(url, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_castfree_link)


    def exit(self):
        print 'index : ' + self.index
        if self.index == 'list_series':
            self.close()
        elif self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'list_series'
            self['menulist'].l.setList(self.series_list)
            self['menulist'].l.setItemHeight(40)

    def get_castfree_link(self,data):
        url = self['menulist'].l.getCurrentSelection()[0][1]
#<script type="text/javascript" src="http://castfree.me/channel.php?a=60&width=100%&height=370&autostart=true"></script>

        castfree_link=re.findall('<script type="text/javascript" src="(http://castfree.me/channel.php.*?)"></script>',data)
        print castfree_link
        if castfree_link:
            castfree_link=castfree_link[0].replace('channel','embed2')
            getPage(castfree_link, headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36','Host': 'castfree.me','Referer': '%s'}).addCallback(self.resolve_castfree, castfree_link) %url

    def resolve_castfree(self,data,url):
        print data
        print url
        name=re.findall("var name.*?=.*?'(.*?)';",data)	
        serverip=re.findall("var edgeserverip = '(.*?)';",data)
        appName=re.findall("var appName  = '(.*?)';",data)
        auth=re.findall('var hlsURL = "http://"\+edgeserverip\+"/"\+appName\+"/"\+name\+"(.*?)";',data)
        if name and serverip:
            print name
            print serverip
            url='http://'+serverip[0]+'/'+appName[0]+'/'+name[0]+auth[0]
            print url
            self.play_channel(url)

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

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/teledunet_poster.jpg'
        try:
            downloadPage(jp_link, tmp_image).addCallback(self.downloadPic, tmp_image)
        finally:
            print 'Error: no data'

    def show_cover(self):
        jpg_link = '/usr/lib/enigma2/python/Plugins/Extensions/teledunet/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 '[teledunet] 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 '[teledunet] no cover.. error'
        return

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


