 # -*- coding: utf-8 -*-
from setup import *
from imports import *
import urllib2
global ua
from cookielib import CookieJar
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Linux; U; Android')]


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


class sportstvclub(Screen):

    def __init__(self, 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()
        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('Sportstv.club')
        self['text'] = Label('')
        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.onLayoutFinish.append(self.abc)

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

    def jobix(self):
        if JobManagerInstalled:
            self.session.open(JobManagerFrontEnd)

    def dnitnow(self):
        if JobManagerInstalled and self.check == 'letter_movie':
            self.dnfile = 'True'
            link = self['menulist'].getCurrent()[0][1]
            self.filmname = self['menulist'].getCurrent()[0][0]
            self.get_play_link(self.filmname, link)

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

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

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

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

    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.index='channels'
        self.loading_ok = False
        self.check = 'abc'
        self.ch_list = []
        self.currentList = 'menulist'
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        sportstv_list=[]
        url = 'http://samdev.club/staging/public/api/free/getcategory'
        data = urllib.urlencode({'app_key' : 'jFutvdixGj'})
        req = urllib2.Request(url, data)
        try:
            response = urllib2.urlopen(req)
            ans = response.read()
        except:
            ans='Page changed again'
        print ans
		#                 "title":"\tVLC","url":"http:\/\/sportstv.club\/main222.php?clrcache=WEB_URL_REMOVE_CACHE____ul li a____1","description":"Vimeo videos","player":"VLC","status":true,"user_agent":"raisam945123"}
        param=re.findall('"title.*?VLC","url":"(.*?)",.*?"player":"VLC","status":true,"user_agent":"(.*?)"',ans)
        print param
        if param:
            global ua
            ua = param[0][1]+' LibVLC/3.0.0-git'
            url= param[0][0].replace('\\','').replace(' ','%20')
            req = urllib2.Request(url)
            response = urllib2.urlopen(req)
            ans = response.read()
            channels=re.findall('<td><a href="(.*?php)"><center><img src="(.*?)" width="150" height="55"/></a></td>',ans)
            for (url,img) in channels:
                title=re.findall('tvhistories\.com/.*?/(.*?)\.[html,php]',url)[0]
                print title
                if title=='tsn1':
                    title='TSN 1'
                if title=='tsn2':
                    title='TSN 2'
                if title=='sportsnetworld':
                    title='SportsNet World'
                if title=='sonyespn':
                    title='Sony ESPN'
                if title=='bein1' or title=='ipl/bein1':
                    title='Bein Sports 1 HD'
                if title=='bein2' or title=='ipl/bein2':
                    title='Bein Sports 2 HD'
                if title=='bein3':
                    title='Bein Sports 3 HD'
                if title=='bein4':
                    title='Bein Sports 4 HD'
                if title=='bein5':
                    title='Bein Sports 5 HD'
                if title=='bein6':
                    title='Bein Sports 6 HD'
                if title=='bein7':
                    title='Bein Sports 7 HD'
                if title=='bein8':
                    title='Bein Sports 8 HD'
                if title=='bein9':
                    title='Bein Sports 9 HD'
                if title=='bein10':
                    title='Bein Sports 10 HD'
                if title=='bein11' or title=='ipl/bein11':
                    title='Bein Sports 11 HD'
                if title=='bein12':
                    title='Bein Sports 12 HD'
                if title=='fr1bein':
                    title='Bein Sports 1 FR'
                if title=='fr2bein':
                    title='Bein Sports 2 FR'
                if title=='fr3bein':
                    title='Bein Sports 3 FR'
                if title=='beinusa':
                    title='Bein Sports USA'
                if title=='beinmax1':
                    title='Bein Sports 1 MAX'
                if title=='beinmax2':
                    title='Bein Sports 2 MAX'
                if title=='frbeinmax4':
                    title='Bein Sports 4 MAX'
                if title=='frbeinmax5':
                    title='Bein Sports 5 MAX'
                if title=='skys1' or title=='ipl/skys1':
                    title='Sky Sports 1'
                if title=='skys2':
                    title='Sky Sports 2'
                if title=='skys3':
                    title='Sky Sports 3'
                if title=='skys4':
                    title='Sky Sports 4'
                if title=='skys5':
                    title='Sky Sports 5'
                if title=='skysf1':
                    title='Sky Sports F1'
                if title=='skysnews':
                    title='Sky Sports News'
                if title=='bundeshliga':
                    title='Sky Bundesliga 1 HD'
                if title=='bt1':
                    title='BT Sports 1'
                if title=='bt2':
                    title='BT Sports 2'
                if title=='bt3':
                    title='BT Sports 3'
                if title=='btespn':
                    title='BT Sports ESPN'
                if title=='itskysports1':
                    title='Sky Sports 1 IT'
                if title=='itskysports2':
                    title='Sky Sports 2 IT'
                if title=='itskysports3':
                    title='Sky Sports 3 IT'
                if title=='itskysports24':
                    title='Sky Sports 24 IT'
                if title=='euro1':
                    title='Eurosport 1'
                if title=='euro2':
                    title='Eurosport 2'
                if title=='espnusa1':
                    title='ESPN USA 1'
                if title=='espnusa2':
                    title='ESPN USA 2'
                if title=='sk1':
                    title='SportKlub 1'
                if title=='sk2':
                    title='SportKlub 2'
                if title=='sk3':
                    title='SportKlub 3'
                if title=='nbcsn':
                    title='NBCSN'
                if title=='premiresports':
                    title='Premiere Sports'
                if title=='nfl':
                    title='NFL'
                if title=='nhl':
                    title='NHL'
                if title=='skysports_german1':
                    title='Sky Sport 1 HD DE'
                if title=='skysports_german2':
                    title='Sky Sport 2 HD DE'
                if title=='btn':
                    title='BTN'
                if title=='wwe':
                    title='WWE'
                if title=='arena1':
                    title='Arena Sport 1'
                if title=='arena2':
                    title='Arena Sport 2'
                if title=='arena3':
                    title='Arena Sport 3'
                if title=='arena4':
                    title='Arena Sport 4'
                if title=='nbcsn':
                    title='NBCSN'
                if title=='setanta':
                    title='Setana'
                if title=='canal':
                    title='CANAL'
                if title=='canalplus':
                    title='CANAL PLUS'
                if title=='fox1usa':
                    title='FOX 1 USA'
                if title=='fox2usa':
                    title='FOX 2 USA'
                if title=='ptv':
                    title='PTV'
                if title=='nlfox1':
                    title='FOX 1 NL'
                if title=='nlfox2':
                    title='FOX 2 NL'
                if title=='nlfox3':
                    title='FOX 3 NL'
                if title=='nlfox4':
                    title='FOX 4 NL'
                if title=='nlfox5':
                    title='FOX 5 NL'
                if title=='attheraces':
                    title='AtTheRaces'
                if title=='racinguk':
                    title='Racing UK'
                if title=='boxnation':
                    title='Boxnation'
                if title=='sporttv1':
                    title='Sport TV 1'
                if title=='sporttv2':
                    title='Sport TV 2'
                if title=='sporttv3':
                    title='Sport TV 3'
                if title=='sonysix':
                    title='Sony SIX'
                if title=='star1':
                    title='Star Sports 1'
                if title=='star2':
                    title='Star Sports 2'
                if title=='star3':
                    title='Star Sports 3'
                if title=='star4':
                    title='Star Sports 4'
                if title=='willow' or title=='ipl/willow':
                    title='Willow'
                if title=='geosuper':
                    title='GeoSuper'
                if title=='chalsea':
                    title='Chelsea TV'
                if title=='channel9':
                    title='Channel 9'
                if title=='ten1':
                    title='TEN 1'
                if title=='ten2':
                    title='TEN 2'
                if title=='ten3':
                    title='TEN 3'
                if title=='gtv':
                    title='GTV'
                if title=='mutv':
                    title='MUTV'
                if title=='nba':
                    title='NBA'
                if title=='channel/ch1':
                    title='Channel 1'
                if title=='channel/ch2':
                    title='Channel 2'
                if title=='channel/ch3':
                    title='Channel 3'
                if title=='channel/ch4':
                    title='Channel 4'
                if title=='channel/ch5':
                    title='Channel 5'
                if title=='channel/ch6':
                    title='Channel 6'
                if title=='channel/ch7':
                    title='Channel 7'
                if title=='channel/ch8':
                    title='Channel 8'
                if title=='channel/ch9':
                    title='Channel 9'
                if title=='channel/ch10':
                    title='Channel 10'
                if title=='channel/ch11':
                    title='Channel 11'
                if title=='channel/ch12':
                    title='Channel 12'
                if title=='channel/ch13':
                    title='Channel 13'
                if title=='channel/ch14':
                    title='Channel 14'
                if title=='channel/ch15':
                    title='Channel 15'
                if title=='channel/ch16':
                    title='Channel 16'
                if title=='channel/ch17':
                    title='Channel 17'
                if title=='channel/ch18':
                    title='Channel 18'
                if title=='channel/ch19':
                    title='Channel 19'
                if title=='channel/ch20':
                    title='Channel 20'
                if title=='sportsnetone':
                    title='SportsNet One'
                if title=='sportsnetonterio':
                    title='SportsNet Onterio'
                if title=='sportsnetworld':
                    title='SportsNet World'
                if title=='extra1':
                    title='Extra 1'
                if title=='extra2':
                    title='Extra 2'
                if title=='extra3':
                    title='Extra 3'
                if title=='extra4':
                    title='Extra 4'
                if title=='astro1':
                    title='Astro Supersport 1'
                if title=='astro2':
                    title='Astro Supersport 2'
                if title=='astro3':
                    title='Astro Supersport 3'
                if title=='tsn1':
                    title='TSN 1'
                if title=='tsn2':
                    title='TSN 2'
                if title=='skymoviesaction':
                    title='Sky Movies Action'
                if title=='skymoviescomedy':
                    title='Sky Movies Comedy'
                if title=='skymoviescrime':
                   title='Sky Movies Crime'
                if title=='skymoviesdrama':
                    title='Sky Movies Drama'
                if title=='skymoviesfamily':
                    title='Sky Movies Family'
                if title=='skymoviesmodern':
                    title='Sky Movies Modern'
                if title=='skymoviespremire':
                    title='Sky Movies Premire'
                if title=='skymoviesscfi':
                    title='Sky Movies SCFI'
                if title=='skymoviesselect':
                    title='Sky Movies Select'
                if title=='skymoviesdisney':
                    title='Sky Movies Disney'
                if title=='skymoviesatlantic':
                    title='Sky Movies Atlantic'
                if title=='bbc1':
                    title='BBC 1'
                if title=='bbc2':
                    title='BBC 2'
                if title=='bbc3':
                    title='BBC 3'
                if title=='bbc4':
                    title='BBC 4'
                if title=='itv1':
                    title='ITV 1'
                if title=='itv2':
                    title='ITV 2'
                if title=='itv3':
                    title='ITV 3'
                if title=='itv4':
                    title='ITV 4'
                if title=='beinmovies1hd':
                    title='Bein Movies 1 HD'
                if title=='beinmovies2hd':
                    title='Bein Movies 2 HD'
                if title=='beinmovies3hd':
                    title='Bein Movies 3 HD'
                if title=='beinmovies4hd':
                    title='Bein Movies 4 HD'

                img='http://sportstv.club'+img
                self.ch_list.append(show_(title,url,img))
            self['menulist'].l.setList(self.ch_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()
        return
		
    def show_streams(self):
        self.index='streams'
        self.stream_list=[]
        uri = self['menulist'].l.getCurrentSelection()[0][1]
        print uri
        res=opener.open(uri)
        ans=res.read()
        channels=re.findall('<p class="White">.*?href=.*?(http.*?)"><h2>(.*?)</h2>',ans,re.DOTALL)
        if channels:
            for (url,title) in channels:#<p class="White"><a href="http://live1.livetvindia.co.in:8000/live/333sdfs3d3fsfd333/sdf23sdr5sdf6r3dds/261.ts?coms"><h2>1) 2G Link</h2></a><p>

                img='http://'
                if not 'Party' in title:
                    self.stream_list.append(show_(title,url,img))
        else:
            channels=re.findall('<br>.*?<a href=" (.*?)">(.*?)</a>',ans,re.DOTALL)
            if channels:
                for (url,title) in channels:
                    img='http://'
                    if not 'Party' in title:
                        title=title.replace('<strong>','').replace('</strong>','')
                        self.stream_list.append(show_(title,url,img))
            else:
                channels=re.findall('<li><a href="(.*?)" align="center">(.*?)</a></li>',ans,re.DOTALL)
                for (url,title) in channels:
                    img='http://'
                    if not 'Party' in title:
                        title=title.replace('<strong>','').replace('</strong>','')
                        self.stream_list.append(show_(title,url,img))
        self['menulist'].l.setList(self.stream_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.show_cover()
        return
        

    def ok(self):
        if self.index=='channels':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            self.show_streams()
        else:
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            self.play_that_shit(uri)           
           

    def play_that_shit(self, data):
        print data
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        if '.ts' in data:
            fin_uri = 'http://127.0.0.1:88/httpstream://' + data + ' headers={"Accept":"*/*","Accept-Language":"en_US","Range":"bytes=0-","User-Agent":"%s"}' %ua
        elif 'm3u8' in data:
            fin_uri = 'http://127.0.0.1:88/hlsvariant://' + data + ' headers={"Accept":"*/*","Accept-Language":"en_US","Range":"bytes=0-","User-Agent":"%s"}' %ua
        sref = eServiceReference(4097, 0, fin_uri)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def exit(self):
        if self.index=='streams':
            self.index='channels'
            self.abc()           
        elif self.index=='channels':
            self.close()

    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: can't find file or read 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(jpg_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 stream_not_found(self):
        message = self.session.open(MessageBox, _('Stream not found, try again later on'), MessageBox.TYPE_INFO, timeout=3)

    def errorload2(self, error):
        print '[teledunet] error %s' % error
        count_movies = len(self.letter_movielist)
        self.loading_ok = True
        self.loading = 0
        self.count = 0

    def errorload(self, error):
        print error

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