# -*- coding: utf-8 -*-
from imports import *
from about import *
import json
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
cj={}
urlMain = "https://cine.to"
urlSearch = "https://cine.to/request/search"
urlMeta = "https://cine.to/request/entry"
urlLinks = "https://cine.to/request/links"
urlPics = "https://s.cine.to/cover/"
urlStream = "https://cine.to/out/"

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,lang):
    res = [(name, link, image,lang)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=6, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


def showhoster_(info, streamid, image, title, imdb):
    res = [(info,
      streamid,
      image,
      title,
      imdb)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, 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 cineto(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,
         'yellow': self.page_plus,
         'blue': self.page_minus,
         'green': self.search,
         }, -1)
        self.index=''
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('Search')
        self['yellow'] = Label(_('Page +'))
        self['blue'] = Label('Page -')
        self['Menu'] = Label('')
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('cine.to')
        self['yellow'].hide()
        self['blue'].hide()
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.dir()
        self.video_list=[]
        self.info=''
        global old_ref
        page=1
        old_ref=self.session.nav.getCurrentlyPlayingServiceReference()
        self.onLayoutFinish.append(self.show_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)
        if self.index == 'movies':
            try:
                self.load_poster()
                info= self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'
				
    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'movies':
            try:
                self.load_poster()
                info= self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'movies':
            try:
                self.load_poster()
                info= self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'movies':
            try:
                self.load_poster()
                info= self['menulist'].getCurrent()[0][3]
                self['text'].setText(info)
            except:
                print 'error loading poster'
				
    def page_plus(self):
        if self.index=='movies':
            global page
            global cat_id
            print 'Page='+str(page)
            query = self.q(cat_id,page)
            data = self.getData(urlSearch,query)
            self.show_movies(data)
			
    def page_minus(self):
        if self.index=='movies':
            global page
            page=int(page)-2
            if page==0:
                page=1
            global cat_id
            print 'Page='+str(page)
            query = self.q(cat_id,page)
            data = self.getData(urlSearch,query)
            self.show_movies(data)
			
    def search(self):
        self.info = 'search'
        self.session.openWithCallback(self.search_cineto, VirtualKeyBoard, title=_('Enter name of the movie'))

    def search_cineto(self, searchstring = None):
        self.info = 'search'
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            query = self.q(0,1,searchstring_fin)
            data = self.getData(urlSearch,query)
            self.show_movies(data)
            url = 'http://stream-oase.tv/search?q=' + searchstring_fin
            getPage(url, timeout=8, headers={'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.show_movies)
		

    def show_cat(self):
        self.index='cat'
        self.cat=[]
        self.cat_list=[('1','Action'),('2','Adventure'),('3','Animation'),('4','Biography'),('5','Comedy'),('6','Crime'),('7','Documentary'),('8','Drama'),('9','Family'),('10','Fantasy'),('11','Film-Noir'),('12','History'),('13','Horror'),('14','Music'),('15','Musical'),('16','Mystery'),('17','Romance'),('18','Sci-Fi'),('19','Sport'),('20','Thriller'),('21','War'),('22','Western'),]
        for (url,title) in self.cat_list:
            self.cat.append(cat_(title,url))
        self['menulist'].l.setList(self.cat)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
		
    def q(self,genre=0, page=1 ,sQ=''):
        yearStart='1913'
        yearEnd='2016'
        imdbRating='1'
        return "kind=all&genre="+str(genre)+"&rating="+imdbRating+"&year%5B%5D="+yearStart+"&year%5B%5D="+yearEnd+"&term="+str(sQ)+"&page="+str(page)+"&count=24"    
		
    def getData(self,url, postData):
        req = urllib2.Request(url,postData)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        req.add_header('Host', 'cine.to')
        req.add_header('Origin', 'https://cine.to')
        req.add_header('Referer', 'https://cine.to')
        response = urllib2.urlopen(req)
        dr = response.read()
        response.close()
        return dr
		
    def getData1(self,url):
        try:
            req = urllib2.Request(url)
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
            if 'streamcloud'in url:
                req.add_header('Host','streamcloud.eu')
            elif 'vivo' in url:
                req.add_header('Host','vivo.sx')
            req.add_header('Referer',url)
            req.add_header('Content-Type','application/x-www-form-urlencoded')
            response = urllib2.urlopen(req)
            dr = response.read()
            response.close()
            return dr
        except:
            return False	
			
    def show_movies(self,data):
        self.index='movies'
        self['yellow'].show()
        self['blue'].show()
        self.movie_list=[]
        jsonContent = json.loads(data)
        for entry in jsonContent['entries']:
            print entry
            languages = entry['language'].split(',')
            qual = entry['quality']
            lang = []
            for ll in languages:
                lang.append(ll[0:2])
            lang.sort()
            l = ",".join(lang)
            title = entry['title']+" ("+l+" "+qual+")"
            picture = "http:"+entry['cover']
            print picture
            self.movie_list.append(show_(title.encode('utf-8'),entry['imdb'].encode('utf-8'),picture.encode('utf-8'),l))
        self['menulist'].l.setList(self.movie_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()
        #if not 'search' in self.info:
        try:
            global page
            page=int(page)+1
        except:
            page='1'
		
    def show_movie_streams(self,title,imdb,lang):
        print 'do nothing'
        self.index='hoster'
        self.hoster=[]
        picture = urlPics + imdb + ".jpg"
        print picture
        for l in lang.split(","):
            print "'"+l+"' imdb " + str(imdb) 
            pd = "ID="+str(imdb)+"&lang="+str(l)
            linkData = self.getData(urlLinks,pd)
            print linkData
            linkDataJSON = json.loads(linkData)
            links = linkDataJSON['links']
            for link in links.iteritems():
                host = link[0]
                qual = link[1][0]
                if len(link[1])>2:
                    del link[1][0]
                count = 1
                for li in link[1]:
                    print li
                    if (str(li) != 'SD') and (str(li) != 'HD'):
                        print host.encode('utf-8')
                        title=l.encode('utf-8')+" "+host.encode('utf-8')+" "+str(count)+" "+qual.encode('utf-8')
                        if host.encode('utf-8')=='streamcloud':
                            self.hoster.append(show_(title,str(li),picture,imdb))
        self['menulist'].l.setList(self.hoster)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)


    def ok(self):
        if self.index=='cat':
            global cat_id
            cat_id=	self['menulist'].l.getCurrentSelection()[0][1]
            global page
            page='1'
            query = self.q(cat_id,page)
            data = self.getData(urlSearch,query)
            self.show_movies(data)
        elif self.index=='movies':
            title=	self['menulist'].l.getCurrentSelection()[0][0]
            imdb=	self['menulist'].l.getCurrentSelection()[0][1]
            lang=	self['menulist'].l.getCurrentSelection()[0][3]
            self.show_movie_streams(title,imdb,lang)
        elif self.index=='hoster':
            streamid=	self['menulist'].l.getCurrentSelection()[0][1]
            imdb=	self['menulist'].l.getCurrentSelection()[0][3]            
            streamUrl = urlStream+str(streamid)
            print streamUrl
            req=urllib2.Request(streamUrl)
            req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36')
            #req.add_header('Origin', 'https://cine.to')
            #req.add_header('Referer', 'https://cine.to')
            f = urllib2.urlopen(req)
            loc=f.geturl()
            print loc
            finalstreamUrl = self.getData1(loc)
            print finalstreamUrl
            if 'streamcloud' in loc:
                form_values = {}
                for i in re.finditer('<input.*?name="(.*?)".*?value="(.*?)">', finalstreamUrl):
                    form_values[i.group(1)] = i.group(2).replace("download1","download2")
                    post = urllib.urlencode(form_values)
                    getPage(loc, method='POST', postdata=post, headers={'Origin':'http://streamcloud.eu','Host':'streamcloud.eu','Referer':'http://streamcloud.eu','Content-Type':'application/x-www-form-urlencoded'}).addCallback(self.get_vid_link)
            elif 'vivo' in loc:
                param1 = re.findall('type="hidden" name="hash".*?value="(.*?)"', finalstreamUrl)[0]
                param2 = re.findall('type="hidden" name="timestamp".*?value="(.*?)"', finalstreamUrl)[0]
                if param1:
                    post = urllib.urlencode({'hash': param1, 'timestamp': param2})
                    getPage(loc, method='POST', postdata=post, headers={'Host':'vivo.sx','Origin':'https://vivo.sx','Referer':'https://vivo.sx/76866110ff','Content-Type':'application/x-www-form-urlencoded'}).addCallback(self.get_vid_link)

    def get_vid_link(self, data):
        #print data
        final_uri = re.findall('class="stream-content" data-url="(.*?)"', data)
        if final_uri:
            self.play_vid(final_uri[0])
        else:
            final_uri=re.findall('file: "(.*?)",',data)
            if final_uri:
                self.play_vid(final_uri[0])

    def exit(self):
        print self.index
        if self.index=='cat':
            self.close()
        elif self.index=='movies':
            self.index='cat'
            self['menulist'].l.setList(self.cat)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)
        elif self.index=='hoster':
            self.index='movies'
            self['menulist'].l.setList(self.movie_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
            auswahl = self['menulist'].getCurrent()[0][0]
            self['name'].setText(auswahl)

    def play_vid(self,data):
        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/hayyes_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/hayyes/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 '[hayyes] 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 '[hayyes] no cover.. error'
        return

    def dir(self):
        if not pathExists('/tmp/hayyes/'):
            os.system('mkdir /tmp/hayyes/')
        else:
            print '[hayyes] /tmp/hayyes/ allready present'
			