# -*- coding: utf-8 -*-
from setup import *
from imports import *
from StringIO import StringIO
import gzip
import requests
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):
    res = [(name, link, image)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


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 kumanda(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('Kumanda.com')
        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_cat)

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

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        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 get_cat(self):
        self.i='cat'
        self.cat_l=[]
        url='https://www.kumanda.tv'
        t=requests.get(url)
        data=t.text
        m_bl=re.findall('<ul id="menu-menu" class="kumandatvmenu">(.*?)</ul>',data,re.DOTALL)
        cat=re.findall('href="(.*?)" title="(.*?)">',m_bl[0])
        for (url,title) in cat:
            url=str(url)
            title=str(title)
            self.cat_l.append(cat_(title,url))
        self['menulist'].l.setList(self.cat_l)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
	
    def get_channels(self):
        self.i='ch'
        self.ch_l=[]
        url=self['menulist'].l.getCurrentSelection()[0][1]
        t=requests.get(url)
        data=t.text
        ch=re.findall('<a href="(.*?)" title="(.*?)"> <img src="(.*?)" alt',data)
        for (url,title,img) in ch:
            url=str(url)
            title=str(title)
            self.ch_l.append(show_(title,url,img))
        self['menulist'].l.setList(self.ch_l)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def get_link(self):
        url=self['menulist'].l.getCurrentSelection()[0][1]
        print url
        headers={'referer':'https://www.kumanda.tv/'}
        t=requests.get(url,headers)
        data=t.text
        print data#<iframe width="100%" height="100%" src="https://www.kumanda.tv/kanallar.php?kanal=ntv&security=c294dc7e9008aff193d75175dfb2641e" frameborder="0" scrolling="no" allowfullscreen></iframe>
        link=re.findall('<iframe width.*?src="(.*?)"',data)
        print link
        if link:
            link=str(link[0])
            print link
            #req = urllib2.Request(link)
            #req.add_header('referer','https://www.kumanda.tv/tv8')
            #req.add_header('accept-encoding','gzip, deflate, sdch, br')
            #req.add_header('user-agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')
            #req.add_header('accept-language','de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
            #req.add_header('cookie','__cfduid=de010a07526ff67e99b47c07f2e4066981489850425; _ga=GA1.2.1537140126.1489851692')
            #resp = urllib2.urlopen(req)
            #buf = StringIO(resp.read())
            #f = gzip.GzipFile(fileobj=buf)
            #try:			
            #    data = f.read()
            #except:
            data = requests.get(link, headers={'referer': 'https://www.kumanda.tv/'}).text			
            print data#file: 'https://zahir.tvizlehd.com/ntv.m3u8?tkn=Ph89o434kOpDgEu6yf2t_A&tms=1497617866',
            file=re.findall("file.*?'(.*?)',",data,re.DOTALL)
            print file
            if file:
                self.play(str(file[0]))
		
    def play(self,link):
        self.i='player'
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        h=' headers={"origin":"https://www.kumanda.tv","referer":"https://www.kumanda.tv/kanallar.php?kanal=atv-canli-izle&security=7a786b0f9ac6246442513e8531c6e58a","user-agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"}'
        if not 'yayin' in link:
            final='http://127.0.0.1:88/hls://'+link.replace('https','http')+h
        else:
            final='http://127.0.0.1:88/hlsvariant://'+link.replace('https','http')+h
        sref = eServiceReference(4097, 0, final)
        sref.setName(selectedName)
        self.session.nav.playService(sref)
        self.hide()
		
    def ok(self):
        if self.i == 'cat':
            self.get_channels()
        elif self.i=='ch':
            self.get_link()
           

    def exit(self):
        print self.i
        if self.i=='cat':
            self.close(self.session, 'exit')
        elif self.i == 'ch':
            self.get_cat()
        elif self.i=='player':
            self.show()
            self.session.nav.playService(old_ref)
            self.i='ch'
            self['menulist'].l.setList(self.ch_l)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
