 # -*- coding: utf-8 -*-
from setup import *
from imports import *
import urllib2
#global ua
#from cookielib import CookieJar
#cj = CookieJar()
#opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#opener.addheaders = [('User-agent', 'Mozilla/5.0 (Linux; U; Android')]


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

    def __init__(self, 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()
        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('Filmcuks.com')
        self['text'] = Label('')
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        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.get_movies)

    def about(self):
        self.session.open(AboutScreen)

    def up(self):
        self[self.currentList].up()
        try:
            self.load_poster()
        except:
            pass

    def down(self):
        self[self.currentList].down()
        try:
            self.load_poster()
        except:
            pass

    def left(self):
        self[self.currentList].pageUp()
        try:
            self.load_poster()
        except:
            pass

    def right(self):
        self[self.currentList].pageDown()
        try:
            self.load_poster()
        except:
            pass

    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 get_movies(self):
        self.index='movies'
        self.m_list=[]
        url='http://www.filmcuks.com'
        req = urllib2.Request(url)
        try:
            response = urllib2.urlopen(req)
            ans = response.read()
        except:
            ans='Page changed again'
        movies=re.findall('<img src="(http://www.filmcuks.com/wp-content/uploads/.*?)" alt="(.*?)" height="100." width="100."/> </a></div><div class="movie-details existing-details"> <span class="movie-title"> <a href="(.*?)" title=".*?" data-wpel-link="internal">.*?</a> </span> <span class="movie-release">',ans)

        for (img,title,url) in movies:
            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()
		
    def get_links(self,data):
        self.index='links'
        self.l_list=[]
        links=re.findall('<span class="hd-icon" title=".*?">(.*?)</span></div></div>.*?href="(.*?)".*?<div class="part-name">(.*?)</div>',data)
        for (quality,url,title) in links:
            self.l_list.append(show_(title,url,'http://'))
        self['menulist'].l.setList(self.l_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)

    def get_hoster(self,data):
        print data
        self.s_list=[]
        self.index='hoster'
        hoster=re.findall('<iframe width="..." height="..." src="(.*?)" frameborder="0" allowfullscreen></iframe></p></div></div>',data)
        if hoster:
            print hoster
            hoster=hoster[0]
            req = urllib2.Request(hoster)
            req.add_header('user-agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36')
            req.add_header('cookie','__cfduid=d23ac4272eb65a9d375d1815d3c4adff91486542528; _pk_ref.1.8a97=%5B%22%22%2C%22%22%2C1486542535%2C%22http%3A%2F%2Fwww.filmcuks.com%2Fuzay-yolculari-passengers.html%2F4%22%5D; video=iframe%2F6n9ed; __auc=8cb255e715a1cd6eca7fc6e4b5a; popup_user_login_uts=yes; _ga=GA1.2.2100152775.1486542532; _pk_id.1.8a97=e448e542d792cf73.1486542535.1.1486542591.1486542535.')
            try:
                response = urllib2.urlopen(req)
                ans = response.read()
            except:
                ans='Page changed again'
            print ans
            streams=re.findall('<source src=\'(.*?)\' type=\'video/mp4\' data-res=\'(.*?)\'',ans)
            print streams
            if streams:
                for (url,quality) in streams:
                    if 'http' in url:
                        url=url
                    else:
                        url='https:'+url
                    self.s_list.append(cat_(quality,url))
            self['menulist'].l.setList(self.s_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)

    def ok(self):
        if self.index=='movies':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            req = urllib2.Request(uri)
            try:
                response = urllib2.urlopen(req)
                ans = response.read()
            except:
                ans='Page changed again'
            self.get_links(ans)
        elif self.index=='links':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            req = urllib2.Request(uri)
            print uri
            try:
                response = urllib2.urlopen(req)
                ans = response.read()
            except:
                ans='Page changed again'
            self.get_hoster(ans)
        else:
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            self.play_that_shit(uri)           
           

    def play_that_shit(self, data):
        print data
        selectedName = self['menulist'].l.getCurrentSelection()[0][0]
        data='http://127.0.0.1:88/'+data
        sref = eServiceReference(4097, 0, data)
        sref.setName(selectedName)
        self.session.open(MoviePlayer, sref)

    def exit(self):
        if self.index=='streams':
            self.index='channels'
            self.abc()           
        elif self.index=='channels':
            self.close()

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