 # -*- coding: utf-8 -*-
from setup import *
from imports import *
import urllib2
from cookielib import CookieJar
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Android 4.2.2')]
#opener.addheaders = [('Cookie',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, 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 show3_(name, link, img, id):
    res = [(name,
      link,
      img,
      id)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


class elahmad(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('elahmad')
        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 = []
        elahmad_list=[]
        self.currentList = 'menulist'
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        elahmad_list=[('1413','Tunisie NAT 1'),
        ('1414','Tunisie NAT 2'),
        ('1404','Zaitouna Tv'),
        ('1418','Tounesna'),
        ('1416','Telvza Tv'),
        ('1415','Nessma Tv'),
        ('1411','Hannibal Tv'),
        ('1394','Attassia tv'),
        ('1409','Al Hiwar Ettounsi'),
        ('1410','FIRST TV'),
        ('1412','M Tunisia'),
        ('1407','AL Janoubia'),
        ('1417','TNN TV'),
        ('1376','Algeria Tv'),
        ('1362','Algeria 3'),
        ('1835','KBC Algeria'),
        ('1884','El Bilad tv'),
        ('1885','El Fadjr Tv Dz'),
        ('1834','EL Djazairia'),
        ('1833','Dzair tv'),
        ('1886','Dzair 24'),
        ('1828','Ennahar tv'),
        ('1649','Ennahar Laki'),
        ('1883','Echorouk TV'),
        ('1401','Samira TV'),
        ('1424','Maroc 2M'),
        ('1425','Aloula Maroc'),
        ('1426','Assadissa'),
        ('1705','Arriadia 3'),
        ('1378','Al jazeera'),
        ('1746','Al jazeera DOC'),
        ('1368','AD Nat Geo HD'),
        ('1408','Al Arabiya'),
        ('1642','France 24 AR'),
        ('1646','Toyor jannah'),
        ('1648','Spacetoon'),
        ('1645','Cartoon Net AR'),
        ('1647','Baraeem'),
        ('1375','Abu Dhabi'),
        ('1703','AD Drama'),
        ('1374','Dubai one'),
        ('1379','MBC 1'),
        ('1380','MBC 2'),
        ('1381','MBC 3'),
        ('1382','MBC 4'),
        ('1386','Mbc masr1'),
        ('1395','Mbc masr2'),
        ('1385','MBC Drama'),
        ('1387','MBC Max'),
        ('1383','MBC Action'),
        ('1363','Art Aflam1'),
        ('1364','Art Aflam2'),
        ('1365','Art Cinema'),
        ('1366','Art Hekayat 2'),
        ('1398','Rotana Cinema'),
        ('1398','Rotana Aflam'),
        ('1399','Rotana Masriya'),
        ('1397','Rotana Classic'),
        ('1423','ZEE Alwan'),
        ('1745','Syria Drama'),
        ('1754','Syria Aloula'),
        ('1403','Star Cinema1'),
        ('1405','Star Cinema2'),
        ('1406','Time Comedy'),
        ('1763','Panorama Drama2'),
        ('1391','Nile Drama'),
        ('1390','Nile Comedy'),
        ('1389','Nile Cinema'),
        ('1753','Sky News ARAb'),
        ('1420','El Mehwer'),
        ('1372','Nahar Drama'),
        ('1643','LBC'),
        ('1369','CBC'),
        ('1830','CBC 2'),
        ('1829','CBC Sofra'),
        ('1371','CBC Drama'),
        ('1419','AlNahar'),
        ('1370','Alhayat1'),
        ('1866','Bein Movies1'),
        ('1867','Bein Movies2'),
        ('1942','Bein Movies3'),
        ('2593','AD Sport 1'),
        ('2594','AD Sport 2'),
        ('2607','AD Sport 3'),
        ('2608','AD Sport 4'),
        ('2609','AD Sport 5'),
        ('2610','AD Sport 6'),
        ('2605','Alkass One'),
        ('2606','Alkass Two'),
        ('2601','Dubai Racing 2'),
        ('2602','Dubai Racing 3'),
        ('2600','Dubai Sport 1'),
        ('2603','Dubai Sport 3'),
        ('2604','Dubai Sport 4'),
        ('2599','Iraqia Sport'),
        ('2595','jordan sport'),
        ('2597','Neelain Sport'),
        ('2596','Nile Sport'),
        ('2598','Saudi Sport'),
        ('2188','DIGI SPORT 1'),
        ('2187','DIGI SPORT 2'),
        ('2186','DIGI SPORT 3'),
        ('2185','DIGI SPORT 4'),
        ('1349','BTSports 01 HD'),
        ('1348','BTSports 02 HD'),
        ('1971','Sport Klub 01HD'),
        ('1970','Sport Klub 02HD'),
        ('1969','Sport Klub 03HD'),
        ('1976','Arena Sport 01 HD'),
        ('1975','Arena Sport 02 HD'),
        ('1974','Arena Sport 03 HD'),
        ('1973','Arena Sport 04 HD'),
        ('1972','Arena Sport 05 HD'),
        ('1952','Bein Sport 01 SD'),
        ('1953','Bein Sport 02 SD'),
        ('1954','Bein Sport 03 SD'),
        ('1955','Bein Sport 04 SD'),
        ('1956','Bein Sport 05 SD'),
        ('1957','Bein Sport 06 SD'),
        ('1958','Bein Sport 07 SD'),
        ('1959','Bein Sport 08 SD'),
        ('1960','Bein Sport 09 SD'),
        ('2611','Bein Sport NEWS'),
        ('971','Bein Sports01 HD'),
        ('972','Bein Sports02 HD'),
        ('973','Bein Sports03 HD'),
        ('974','Bein Sports04 HD'),
        ('975','Bein Sports05 HD'),
        ('976','Bein Sports06 HD'),
        ('977','Bein Sports07 HD'),
        ('978','Bein Sports08 HD'),
        ('979','Bein Sports09 HD'),
        ('980','Bein Sports10 HD'),
        ('981','Bein Sports11 HD'),
        ('982','Bein Sports12 HD'),
        ('984','Bein Sports13 HD'),
        ('985','Bein Sports14 HD'),
        ('986','Bein Sports15 HD'),
        ('1937','Bein Sports16 HD'),
        ('1892','bein Max1'),
        ('1893','bein Max2'),
        ('1145','Bein Sports1 FR HD'),
        ('1146','Bein Sports2 FR HD'),
        ('971','Bein Sports3 FR HD'),
        ('1912','Real Madrid ch'),
        ('1916','FOX SPORTS HD'),
        ('1923','Canal Toros HD'),
        ('1924','Canal Liga HD'),
        ('1925','Canal Futbol HD'),
        ('1159','Sport1 DE'),
        ('1157','SkySports1 DE'),
        ('1158','SkySports2 DE'),
        ('1281','SkySport1HD iT'),
        ('1283','SkySport2HD iT'),
        ('1284','SkySport3HD iT'),
        ('1020','Foot+ 24/24'),
        ('1036','C+ Sport HD'),
        ('1022','Eurosport 1 HD'),
        ('1021','Eurosport 2 HD'),
        ('1042','OL tv'),
        ('1012','Info Sport HD'),
        ('1007','Ma Chaine Sport HD'),
        ('1693','SuperSport 1HD'),
        ('1692','SuperSport 2HD'),
        ('1691','SuperSport 3HD'),
        ('1690','SuperSport 4HD'),
        ('1324','SkySports1 UK'),
        ('1323','SkySports2 UK'),
        ('1322','SkySports3 UK'),
        ('1321','SkySports4 UK')]
        for (url,title) in elahmad_list:
            self.ch_list.append(show_(title,url,None))
        self['menulist'].l.setList(self.ch_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        #self.show_cover()
        return
		
    def show_streams(self,id):
        #self.index='streams'
        self.stream_list=[]
        uri = 'http://www.elahmad.com/tv/mobiletv/watch.php'
        print uri
        opener.addheaders = [('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')]
        opener.addheaders = [('Accept-Language','de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')]
        opener.addheaders = [('Cache-Control','max-age=0')]
        opener.addheaders = [('Connection','keep-alive')]
        opener.addheaders = [('Cookie','__test; PHPSESSID=103d420ffeee901485155d392b3c4ca3; __PPU_SESSION_1_654759_false=1489926236548|1|1489926236548|1|1; _gat=1; _ga=GA1.2.1612491895.1489926193')]
        opener.addheaders = [('Host','www.elahmad.com')]
        opener.addheaders = [('Referer','http://www.elahmad.com/tv/mobiletv/?page=2')]
        opener.addheaders = [('Upgrade-Insecure-Requests','1')]
        opener.addheaders = [('User-Agent','Android')]
        res=opener.open(uri)
        ans=res.read()
        print ans#post("/tv/result/teleweb.php
        #next_page=re.findall('/tv/result/teleweb\.php\?v=(.*?)"',ans)
        #print next_page
        #print cj
        #if next_page:
        post={ 'id' : id}
        post=urllib.urlencode(post)
        print post
        url='http://www.elahmad.com/tv/result/teleweb.php'#?v='+next_page[0]
        req = urllib2.Request(url,data=post)
        req.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
        req.add_header('Accept-Language','de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
        req.add_header('Cache-Control','max-age=0')
        req.add_header('Connection','keep-alive')
        req.add_header('Cookie','PHPSESSID=sbndeur24t573bdkln1kl51rl0; _gat=1; _ga=GA1.2.505140044.1477905704')
        req.add_header('Host','www.elahmad.com')
        req.add_header('Referer','http://www.elahmad.com/tv/mobiletv/?page=2')
        req.add_header('Upgrade-Insecure-Requests','1')
        req.add_header('User-Agent','Android')
        page = urllib2.urlopen(req)
        response = page.read() 
        print response			
        self.play_that_shit(response)
        

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

    def play_that_shit(self, data):
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        if '.ts' in data:
            fin_uri = 'http://127.0.0.1:88/httpstream://' + data + ' headers={"User-Agent":"raisam945sam LibVLC/3.0.0-git"}'
        elif 'm3u8' in data:
            fin_uri = 'http://127.0.0.1:88/hlsvariant://' + data + ' headers={"User-Agent":"raisam945sam LibVLC/3.0.0-git"}'
        sref = eServiceReference(4097, 0, fin_uri)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def exit(self):
        print self.index
        if self.index=='channels':
#            self.abc()
#        else:
            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'