from setup import *
from about import *
from imports import *
fav_file='/usr/lib/enigma2/python/Plugins/Extensions/Albatros/fav_streamcloud'

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 streamcloud_paste(Screen):

    def __init__(self, session):
        global old_ref
        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,
         'green': self.addtofav,
         'blue': self.openfav,
         'yellow': self.search,
         'cancel': self.exit}, -1)
        self['menulist'] = m2list([])
        self['poster'] = Pixmap()
        self['title'] = Label('Streamcloud')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('Add to FAV')
        self['yellow'] = Label(_('Search'))
        self['blue'] = Label('OPEN FAV')
        self['Menu'] = Label(_(' '))
        self['name'] = Label('')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.dir()
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.get_bs_abc)
		
    def addtofav(self):
        title = self['menulist'].l.getCurrentSelection()[0][0]
        url = self['menulist'].l.getCurrentSelection()[0][1]
        f = open(fav_file,'a+')
        f.write('title:'+title+';url='+url+'end')
        f.close()     
	
    def openfav(self):
        with open(fav_file, "r") as ins:
            array = []
            for line in ins:
                array.append(line)
            print array
        self.index = 'list_series'
        self.series_list = []
        ser=re.findall('title:(.*?);url=(.*?)end',str(array))
        for title,url in ser:
            self.series_list.append(cat_(title, url))
        self['menulist'].l.setList(self.series_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
		
    def about(self):
        self.session.open(AboutScreen)

    def up(self):
        self.cur_idx = int(self['menulist'].getSelectedIndex())
        comp = int(len(self.series_list))
        print 'list : ' + str(comp)
        print self.cur_idx
        if self.cur_idx == 0:
            print 'moving to last idx'
            self['menulist'].moveToIndex(comp - 1)
        else:
            self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        self.cur_idx = int(self['menulist'].getSelectedIndex())
        comp = int(len(self.series_list))
        if self.cur_idx == comp - 1:
            self['menulist'].moveToIndex(0)
        else:
            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_bs_abc(self):
        url='http://pastebin.com/u/Bombaybobby'
        self.series_list = []
        max_nr = 99
        i = 1
        for i in range(1, max_nr):
            url = url + '/' + str(i)
            print url
            getPage(url, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.list_posts)
            i += 1
            url = 'http://pastebin.com/u/Bombaybobby'
        #i=1
        #for i in range(100):
        #    #url=url+str(i)
        #    print url


    def list_posts(self, data):
        self.index = 'list_series'
        posts=re.findall('<a href="(.*?)">(.*?)</a></td>',data)
        for (url,title) in posts:
            url='http://pastebin.com'+url
            if not 'text' in url:
                self.series_list.append(cat_(title, url))
        self['menulist'].l.setList(self.series_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

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

    def search_pastebin(self, searchstring = None):
        self.index='search'
        self.search_list = []
        newlist=[]
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            print searchstring
            r = re.compile("((.*@.*){(%s),)" % re.escape(searchstring))
            print r
            print r.match
            newlist = filter(str(r.match), self.series_list)
            print newlist
            #    if searchstring in item:
            #        print item
            #        for (title,url) in item:
            #            self.search_list.append(cat_(title,url))
            self['menulist'].l.setList(newlist)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
			
			

			
    def ok(self):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        print url
        if self.index == 'list_series':
            getPage(url, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_streamcloud_link)


    def exit(self):
        print 'index : ' + self.index
        if self.index == 'list_series':
            self.close()
        elif self.index == 'search':
            self.get_bs_abc()
        elif self.index == 'player':
            self.show()
            self.session.nav.playService(old_ref)
            self.index = 'list_series'
            self['menulist'].l.setList(self.series_list)
            self['menulist'].l.setItemHeight(40)

    def get_streamcloud_link(self,data):
        url = self['menulist'].l.getCurrentSelection()[0][1]
        streamcloud_link=re.findall('<li class="li1"><div class="de1">(http://streamcloud.eu/.*?)</div></li>',data)
        print streamcloud_link
        if streamcloud_link:
            getPage(streamcloud_link[0], headers={'Cookie':'FastPopSessionRequestNumber=2; lang=german; __atuvc=6%7C44; __utma=5658353.1209786168.1476548407.1478019364.1478026830.3; __utmb=5658353.3.10.1478026830; __utmc=5658353; __utmz=5658353.1476548407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)','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': '%s'}).addCallback(self.resolve_streamcloud, streamcloud_link[0]) %url

    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):
        final_uri = re.findall('file: "(.*?)",', data)
        if final_uri:
            self.play_channel(final_uri[0])


    def play_channel(self, data):
        self.index = 'player'
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.nav.playService(sref)
        self.hide()

    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: no 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/ exists'