# -*- coding: utf-8 -*-
from setup import *
from imports 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, 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 filmestreamz(Screen):

    def __init__(self, session):
        sz_w = getDesktop(0).size().width()
        if sz_w == 1920:
            path = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/defaultListScreen_new.xml'
        else:
            path = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros/skin/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('filme-streamz')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label(_('Search'))
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.m_list=[]
        self.currentList = 'menulist'
        self.menulist = []
        self.dir()
        self.onLayoutFinish.append(self.list_cat)
		
    def up(self):
        self[self.currentList].up()
        if self.idx=='movies':
            self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        self[self.currentList].down()
        if self.idx=='movies':
            self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)


    def left(self):
        self[self.currentList].pageUp()
        if self.idx=='movies':
            self.load_poster()

    def right(self):
        self[self.currentList].pageDown()
        if self.idx=='movies':
            self.load_poster()

    def list_cat(self):
        self.idx='cat'
        self.c_list=[]
        genre_list=[("/genre/43/Abenteuer-stream-p1.html","Abenteuer"),
        ("/genre/1/Action-stream-p1.html","Action"),
        ("/genre/2/Animation-stream-p1.html","Animation"),
        ("/genre/44/Biografie-stream-p1.html","Biografie"),
        ("/genre/52/Bollywood-stream-p1.html","Bollywood"),
        ("/genre/14/Dokumentation-stream-p1.html","Dokumentation"),
        ("/genre/16/Drama-stream-p1.html","Drama"),
        ("/genre/21/Familie-stream-p1.html","Familie"),
        ("/genre/22/Fantasy-stream-p1.html","Fantasy"),
        ("/genre/24/History-stream-p1.html","History"),
        ("/genre/17/Horror-stream-p1.html","Horror"),
        ("/genre/37/Kom%C3%B6die-stream-p1.html","Komödie"),
        ("/genre/23/Kriegsfilme-stream-p1.html","Kriegsfilme"),
        ("/genre/30/Krimi-stream-p1.html","Krimi"),
        ("/genre/27/Musik-stream-p1.html","Musik"),
        ("/genre/55/Mystery-stream-p1.html","Mystery"),
        ("/genre/31/Romanze-stream-p1.html","Romanze"),
        ("/genre/32/Science+fiction-stream-p1.html","Science fiction"),
        ("/genre/48/Spionage-stream-p1.html","Spionage"),
        ("/genre/54/sport+-+Kampfkunst-stream-p1.html","sport - Kampfkunst"),
        ("/genre/35/Thriller-stream-p1.html","Thriller"),
        ("/genre/47/Tragikom%C3%B6die-stream-p1.html","Tragikomödie"),
        ("/genre/36/Western-stream-p1.html","Western")]
        for (url,title) in genre_list:
            url='http://www.filme-streamz.com'+url
            self.c_list.append(cat_(title,url))
        self['menulist'].l.setList(self.c_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

#    def get_pages(self,data):
#        page_max=re.findall('<li class="cursorpointer"><a href="javascript:void\(0\)">...</a></li>.*?<li class="cursorpointer" onclick="window.location = \'.*?-stream-p(.*?).html\'">',data,re.DOTALL)
#        if page_max:
#            page_min=1
#            page_max=int(page_max[0])
#            for i in range(page_min,page_max):
#                url=url.replace('p1','p%s') %str(i)			

    def get_movies(self,data):
        self.idx='movies'
        movies=re.findall('<li class="imgborder" style="">.*?<a href="(.*?)" title="(.*?)">.*?<div class="list_film">.*?<img src="(.*?)" width="',data,re.DOTALL)
        for (url,title,img) in movies:	
            url='http://www.filme-streamz.com'+url
            self.m_list.append(show_(title,url,img))
        self['menulist'].l.setList(self.m_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
			
    def list_hosters(self,data):
        self.idx='hosters'
        self.h_list=[]
        hosters=re.findall('<a href="(.*?)" target="videoPlayer"',data)
        for hoster in hosters:
            if 'flashx' in hoster:
                title='Flashx'
            if 'thevideo' in hoster:
                title='TheVideo'
            if 'vidup' in hoster:
                title='Vidup'
            if 'vidgg' in hoster:
                title='Vidgg'
            self.h_list.append(cat_(title,hoster))
        self['menulist'].l.setList(self.h_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def ok(self):
        if self.idx=='cat':
            url = self['menulist'].getCurrent()[0][1]
            getPage(url, timeout=15, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_movies)            
        if self.idx=='movies':
            url = self['menulist'].getCurrent()[0][1]
            getPage(url, timeout=15, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_hosters)
        if self.idx=='hosters':
            url = self['menulist'].getCurrent()[0][1]
            print url
            self.resolve_link(url)

    def exit(self):
        if self.idx=='cat':
            self.close()
        elif self.idx=='movies':
            self.list_cat()
        elif self.idx=='hosters':
            self.idx='movies'
            self['menulist'].l.setList(self.m_list)
            		

    def resolve_link(self,url):
        if 'flashx' in url:
            self.resolve_flashx(url)
        if 'thevideo' in url:
            self.resolve_thevideo(url)		
        if 'vidup' in url:
            self.resolve_vidup(url)
        if 'vidgg' in url:
            self.resolve_vidgg(url)
			
    def resolve_flashx(self,url):
        url=url.replace('embed-','embed.php?c=').replace('-620x330.html','')
        print url
        getPage(url, timeout=15, headers={'Host':'www.flashx.tv','User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'	}).addCallback(self.get_flashx)
	
    def get_flashx(self,resp):
        print resp
        link=re.findall('<a href="(.*?)" title="',resp)
        print link
        if link:
            getPage(link[0], timeout=15, headers={'Host':'www.flashx.tv','User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'	}).addCallback(self.get_flashx1)

    def get_flashx1(self,resp):
            script=re.findall('<script type=\'text/javascript\'>(eval\(function\(p,a,c,k,e,d\).*?)\n</script>',resp)
            script=jsunpacker.unpack(script[0])
            file=re.findall('file:"(.*?)",label:"Middle"',resp)
            if file:
                self.play_ch(file[0])			
    def resolve_thevideo(self,url):
        getPage(url, timeout=15, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_thevideo)
		
    def get_thevideo(self,resp):
        file=re.findall('\[\{"file":"(.*?)","',resp)
        if file:
            self.play_ch(file[0])
    def resolve_vidgg(self,url):
        getPage(url, timeout=15, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_vidgg)

    def get_vidgg(self,resp):
        file=re.findall('<source src="(.*?)" type=\'video/mp4\'>',resp)
        if file:
            self.play_ch(file[0])
    def resolve_vidup(self,url):
        getPage(url, timeout=15, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_vidup)

    def get_vidup(self,resp):
        file=re.findall('\[\{"file":"(.*?)","',resp)
        if file:
            self.play_ch(file[0])

    def play_ch(self, data):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)
		
    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(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/ allready present'