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 streamkiste(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,
         'green': self.search,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('Streamkiste')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label(_('Search'))
        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()
        if self.idx=='2':
            self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)


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


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

    def right(self):
        self[self.currentList].pageDown()
        if self.idx=='2':
            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 = '1'
        self.loading_ok = False
        self.check = 'abc'
        self.currentList = 'menulist'
        self.letter_movielist = []
        self['menulist'].selectionEnabled(1)
        self['menulist'].show()
        self.genre_name = 'Al Cinema'
        uri='http://streamkiste.tv/cat/action/'
        print uri
        getPage(uri, timeout=15, method='GET', headers={'Host':'streamkiste.tv','Referer':'http://streamkiste.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.load_data_cat)

    def load_data_cat(self, data):
        self.idx='1'
        self.cat_list = []
        #print data
        cat=re.findall('<li class="cat-item cat-item-.*?"><a href="(.*?)" title=".*?">(.*?)</a>',data)
        print cat
        for (url,title) in cat:
            self.cat_list.append(cat_(title, url))
        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def load_data_movies(self,data):
        self.idx='2'
        self.m_list = []
        movies=re.findall('href="(.*?)">\n<span class="center-icons"><span class="icon-hd full tooltip-w" title=".*?src="(.*?)" class="attachment-thumbnail size-thumbnail wp-post-image" title="(.*?)"/></a>',data)
        print movies
        if movies:
            for (url,img,title) in movies:
                title=title.replace('&#8211;','-').replace('&#8217;','\'').replace('amp;','')
                self.m_list.append(show_(title, url, img))
        self['menulist'].l.setList(self.m_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def list_hoster(self,data):
        self.idx='3'
        self.h_list=[]
        hoster=re.findall('<li class="stream"><div id="stream-links"><a href="(.*?)" title=".*?StreamCloud.eu.*?" target="_blank">(.*?)</a></div>',data)        	
        for (url,title) in hoster:
            self.h_list.append(cat_(title, url))
        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 resolve_streamcloud(self,data,url):
        print data
        print url
        op=re.findall('<input type="hidden" name="op" value="(.*?)">',data)
        usr_login=re.findall('<input type="hidden" name="usr_login" value="(.*?)">',data)
        id=re.findall('<input type="hidden" name="id" value="(.*?)">',data)
        fname=re.findall('<input type="hidden" name="fname" value="(.*?)">',data)
        referer=re.findall('<input type="hidden" name="referer" value="(.*?)">',data)
        hash=re.findall('<input type="hidden" name="hash" value="(.*?)">',data)
        imhuman=re.findall('<input type="submit" name="imhuman" id="btn_download" class="button gray" value="(.*?)">',data)
        if id:
            form_values = {'op':'download2','usr_login':'','id':id[0],'fname':fname[0],'referer':'','hash':'','imhuman':imhuman[0]}
            post = urllib.urlencode(form_values)
            print post
            getPage(url, method='POST', postdata=post, headers={'Origin': 'http://streamcloud.eu',
            'Host': 'streamcloud.eu',
            'Referer': '%s',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_vid_link) %url 

    def get_vid_link(self, data):
        print data
        final_uri = re.findall('file: "(.*?)",', data)
        if final_uri:
            self.play_that_shit(final_uri[0])		

    def search(self):
        self.index='search'
        self.session.openWithCallback(self.search_streamoase, VirtualKeyBoard, title=_('Enter name of the movie'))

    def search_streamoase(self, searchstring = None):
        self.index='search'
        self.search_list = []
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            url = 'http://streamkiste.tv/?s=' + searchstring_fin
            getPage(url, timeout=8, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        self.idx='search_data'
        movie=re.findall('<a href="(.*?)">\n<span class="center-icons"><span class=".*?src="(.*?)".*?title="(.*?)"/></a>',data,re.DOTALL)
        if movie:
            for each in movie:
                url, img, title = each
                print title
                self.search_list.append(show_(title, url, img))
            self['menulist'].l.setList(self.search_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()

    def ok(self):
        if self.idx == '1':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(url, timeout=8, headers={'Host':'streamkiste.tv','Referer':'http://streamkiste.tv/','Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.load_data_movies)
        elif self.idx == '2':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(url, timeout=8, headers={'Host':'streamkiste.tv','Referer':'http://streamkiste.tv/','Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_hoster)
        elif self.idx=='search_data':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(uri, timeout=8, method='GET', headers={'Host':'streamkiste.tv','Referer':'http://streamkiste.tv/','User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
            'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_hoster)
        elif self.idx=='3':
            url = self['menulist'].l.getCurrentSelection()[0][1]
            print url
            getPage(url, timeout=8, headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36','Host': 'streamcloud.eu','Referer': 'http://streamcloud.eu'}).addCallback(self.resolve_streamcloud,url)


    def play_that_shit(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 exit(self):
        if self.index=='1':
            self.close()
        elif self.index=='2':
            self.index = '1'
            self['menulist'].l.setList(self.letter_list)
            self['menulist'].l.setItemHeight(40)
            self.load_poster() 
        elif self.index=='search_data':
            self.close()
        elif self.index=='list_streams':
            self.index='search_data'
            self['menulist'].l.setList(self.search_list)
            self['menulist'].l.setItemHeight(40)
            self.load_poster()
        elif self.index=='search_data':
            self.index='search'
            self.search()
        elif self.index=='search':
            self.index='1'
            self.abc()
            		

    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'