from setup import *
from imports import *
from StringIO import StringIO
import gzip

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,info):
    res = [(name, link, img,info)]
    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 movietown(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('Movietown')
        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()
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        info = self['menulist'].getCurrent()[0][3]
        self['name'].setText(auswahl)
        self['text'].setText(info)

    def down(self):
        self[self.currentList].down()
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        info = self['menulist'].getCurrent()[0][3]
        self['name'].setText(auswahl)
        self['text'].setText(info)

    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 = '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://movietown.org/titles/paginate?_token=32vE8dn1WPJck87DDDzwbyl6W8GOiGgS4XHrDRkh&perPage=500&page=1&order=release_dateDesc&type=movie&minRating=&maxRating=&availToStream=true'
        print uri
        getPage(uri, timeout=15, method='GET', headers={'Host':'movietown.org','Referer':'http://movietown.org/movies','User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36','X-Requested-With':'XMLHttpRequest'}).addCallback(self.load_data_channels)
#'Host':'movietown.org','Referer':'http://movietown.org/movies','User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36','X-Requested-With':'XMLHttpRequest'
    def load_data_channels(self, data):
        self.letter_list = []
        print data
        import json
        j = json.loads(data)
        js = json.loads(data)
        parent =  j["items"]
        print parent
        for item in parent:
            title=str(item["title"])
            print title
            url=str(item["link"])
            #print url
            url= re.findall('u\'url\': u\'(.*?)\'',url)
            if url:
                print url
                url=url[0]
            #print url
                info=str(item["plot"])
                print info
                img=str(item["poster"])
                print img
                #url='shit not yet'
                #parent1 = js["items"]["link"]
                #for item in parent1:
                #    url = str(item["url"])
                #    print url
                self.letter_list.append(show_(title, url, img,info))
        self['menulist'].l.setList(self.letter_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        info = self['menulist'].getCurrent()[0][3]
        self['name'].setText(auswahl)
        self['text'].setText(info)
		
    def get_episodes(self,data):
        print data
        self.index='2'
        self.episodes_list=[]
        episodes=re.findall('<td style="float:left;text-align:left;margin-left:..px; "width=".*?"><a href="(.*?)">(.*?)</a></td>.*?<td width=".*?"><a href=".*?"><img src="(.*?)" /></a></td>',data,re.DOTALL)
        for each in episodes:
            url,title,img=each
            self.episodes_list.append(show_(title, url, img))
        self['menulist'].l.setList(self.episodes_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()
        return

    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://movietown.org/search?q=' + searchstring_fin
            getPage(url, timeout=8, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)

    def search_data(self, data):
        self.index='search_data'
        block=re.findall('<h2>Movies</h2>(.*?)<h2>Series</h2>',data,re.DOTALL)
        search = re.findall('<a href="(.*?)"><img class ="img-responsive" src="(.*?)" alt="(.*?)"></a>',block[0])
        print search
        if search:
            for each in search:
                url, img, title = each
                print title
                self.search_list.append(show_(title, url, img,None))
            self['menulist'].l.setList(self.search_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()

    def list_streams(self, data):
        self.vid_list=[]
        self.index='list_streams'
        urls=re.findall('<td class="name hover" data-bind="click: playVideo.bind\(\$data, \'(.*?)\', \'embed\'\)"><img data-bind="attr: \{src: app\.utils\.getFavicon\(\'(.*?)\'\)\}">(.*?)</td>.*?<td>(.*?)</td>',data,re.DOTALL)
        print urls
        if urls:
            for each in urls:
                vidurl,img,title,title_add = each
                title=title+' '+title_add
                print title
                if 'streamcloud' in vidurl:
                    self.vid_list.append(show_(title, vidurl, img, None))
            self['menulist'].l.setList(self.vid_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            self.load_poster()			
		
	

    def get_hls(self, url):
        print url
        getPage(url, timeout=8, method='GET', headers={'host':'streamcloud.eu','Referer':'http://stream-oase.tv/movies/39-the-dark-knight','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.get_hls_2,url)
		 
    def get_hls_2(self, data,url):
        print 'get_hls_2'
        print data
        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_that_shit(final_uri[0])

    def ok(self):
        if self.index == '1':
            final_uri = self['menulist'].l.getCurrentSelection()[0][1]
            self.get_hls(final_uri)
        elif self.index == '2':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            self.get_hls_2(uri)
        elif self.index=='search_data':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            getPage(uri, timeout=8, method='GET', headers={'Referer':'http://stream-oase.tv/movies/39-the-dark-knight','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_streams)
        elif self.index=='list_streams':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            self.get_hls(uri)


    def play_that_shit(self, data):
        selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        #link = re.findall('file: \'(.*?)\',', data)
        #if link:
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)
        #else:
        #    print data


    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 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'