import requests,re
from imports import *
from about import *

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 hdfreetv(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('hdfree.tv')
        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.get_channels)

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

    def up(self):
        if self.info == 'get_channels':
            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 == 'get_channels':
            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 == 'get_channels':
            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 == 'get_channels':
            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 get_channels(self):
        self.info='get_channels'
        self.show_list=[]
        data=requests.get('http://hdfree.tv/tvlogos.html').text
        channels=re.findall('<a href="(.*?)" target="fdf" class="imgvisited1"><img src="(.*?)" width="150" height="27" border="0"></a>',data)
        for (url,img) in channels:
            title=re.findall('//.*?/watch/.*?/(.*?)-live-stream',str(url))
            title=str(title).upper().replace("['","").replace("']","")
            img='http://hdfree.tv/'+str(img)
            if title=='[]':
                title='Schedule'
            self.show_list.append(show_(title,str(url),img,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 get_schedule(self):
        self.info='get_channels'
        self.sch_list=[]
        data=requests.get('http://hdfree.tv').text
        print data
        channels=re.findall('img src="(.*?)".*?width="32">(.*?)</span>.*?"panel-title">(.*?)</h3>.*?href=\'(.*?)\' class',data,re.DOTALL)
        for (img,mtime,title,url) in channels:
            title=str(mtime)+' : '+str(title)
            self.sch_list.append(show_(title,str(url),str(img),None))
        self['menulist'].l.setList(self.sch_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)


    def get_link(self,url):
        print url
        if url=='http://hdfree.tv':
            self.get_schedule()
        else:		
            data=requests.get(url).text
            iframe_code=re.findall('<iframe frameborder="0" marginheight="0" marginwidth="0" height="490" id="iframe" src="(.*?)" id="myfr"',data)
            if iframe_code:
                data=requests.get(iframe_code[0]).text
                var=re.findall('<script type=\'text/javascript\'> width=(.*?), height=(.*?), channel=\'(.*?)\', g=\'(.*?)\';</script><script type=\'text/javascript\' src=\'http://www.cast4u.tv/static/scripts/cast4u.js\'></script>',data)
                if var:
                    channel=var[0][2]
                    g=var[0][3]
                    width=var[0][0]
                    height=var[0][1]

                    url="http://www.cast4u.tv/membedplayer/"+channel+"/"+g+"/"+width+"/"+height
                    src_page=requests.get(url,headers={"Referer":"http://hdfree.tv"}).text
                    ea=requests.get('http://live.cast4u.tv:1935/loadbalancer').text
                    if ea:
                        ea=re.findall( r'[0-9]+(?:\.[0-9]+){3}',ea,re.DOTALL)
                        att2=re.findall('setAttribute.*?ea.*?"(.*?)"',src_page) 
                        if ea and att2:
                            fin='http://'+str(ea[0])+str(att2[0])
                            self.play_movie(fin)

    def play_movie(self, link):
        self.info='player'
        if 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):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        sel = self['menulist'].l.getCurrentSelection()[0][0]
        if self.info == 'get_channels':
            self.get_link(url)

    def exit(self):
        print self.info
        if re.match('(get_channels)', self.info, re.S | re.I):
            self.close(self.session, 'exit')
        elif self.info=='player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info='get_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'