# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/Albatros/kino24.py
from imports import *
from about import *
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'

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):
    res = [(name, link, image)]
    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 kino24(Screen):

    def __init__(self, session):
        global old_ref
        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}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_('About'))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label('')
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('kino24.me')
        self.currentList = 'menulist'
        self.menulist = []
        self.m_list = []
        self.dir()
        self.index = ''
        old_ref = self.session.nav.getCurrentlyPlayingServiceReference()
        self.get_cat()

    def about(self):
        self.about()

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_mlist':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def down(self):
        self[self.currentList].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_mlist':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def left(self):
        self[self.currentList].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_mlist':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def right(self):
        self[self.currentList].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.index == 'get_mlist':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def get_cat(self):
        self.index = 'get_cat'
        self.cat_list = []
        self.cat = [('Action', 'http://kino24.me/action/'),
         ('Drama', 'http://kino24.me/drama/'),
         ('Comedy', 'http://kino24.me/comedy/'),
         ('Horror', 'http://kino24.me/horror/'),
         ('Thriller', 'http://kino24.me/thriller/'),
         ('Sci-Fi', 'http://kino24.me/sci-fi/'),
         ('Adventure', 'http://kino24.me/adventure/'),
         ('Crime', 'http://kino24.me/crime/'),
         ('Animation', 'http://kino24.me/animation/'),
         ('Dokumentation', 'http://kino24.me/dokumentation/'),
         ('History', 'http://kino24.me/history/'),
         ('Fantasy', 'http://kino24.me/fantasy/'),
         ('Western', 'http://kino24.me/western/')]
        for title, url in self.cat:
            self.cat_list.append(cat_(title, url))

        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)

    def get_mlist(self, data):
        self.index = 'get_mlist'
        movies = re.findall('<div class="short-imghover" style="background-image\\:url\\((.*?)\\),.*?<a href="(.*?)">Watch</a>.*?<a href=".*?">(.*?)</a><br>', data, re.DOTALL)
        print movies
        for img, url, title 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_hosters(self, data):
        hoster = re.findall('<div id="re-video">.*?<a href="(.*?)" target="_blank">', data, re.DOTALL)
        print hoster
        if hoster:
            header = [('User-Agent', '')]
            new_data = getUrl(hoster[0], headers=header, post=None, jsonpost=False)
            print new_data
            file = re.findall('file: "(.*?)",', new_data)
            if file:
                self.play_channel(file[0])
        return

    def play_channel(self, data):
        selected = self['menulist'].getCurrent()[0][0]
        sref = eServiceReference(4097, 0, data)
        sref.setName(selected)
        self.session.open(MoviePlayer, sref)

    def ok(self):
        if self.index == 'get_cat':
            url = self['menulist'].getCurrent()[0][1]
            header = [('User-Agent', '')]
            page = getUrl(url, headers=header, jsonpost=False)
            max_page_nr = re.findall('\\.\\.\\.</span> <a href="http://kino24.me/.*?">(.*?)</a></li>', page)
            print max_page_nr
            if max_page_nr:
                max_nr = int(max_page_nr[0]) + 1
                print max_nr
                i = 1
                for i in range(1, max_nr):
                    url = str(url) + 'page/' + str(i) + '/'
                    print url
                    try:
                        getPage(url, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
                         'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_mlist)
                        i += 1
                        url = self['menulist'].getCurrent()[0][1]
                    except:
                        pass

            else:
                getPage(url, timeout=8, method='GET', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
                 'Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.get_mlist)
        elif self.index == 'get_mlist':
            url = self['menulist'].getCurrent()[0][1]
            header = [('User-Agent', '')]
            page = getUrl(url, headers=header, jsonpost=False)
            self.get_hosters(page)
        elif self.index == 'get_hosters':
            url = self['menulist'].getCurrent()[0][1]
            self.play_channel(url)

    def exit(self):
        if self.index == 'get_cat':
            self.close()
        elif self.index == 'get_mlist':
            self.index = 'get_cat'
            self.m_list[:] = []
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/albatros/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 = '/tmp/albatros/poster.jpg'
        jpg_name = '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 '[Albatros] 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 '[WWE] no cover.. error'
        return

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


def getUrl(url, cookieJar = None, post = None, timeout = 20, headers = None, returnResponse = False, noredirect = False, jsonpost = False):
    cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
    opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
    if jsonpost:
        req.add_header('Content-Type', 'application/json')
    if headers:
        for h, hv in headers:
            req.add_header(h, hv)

    response = opener.open(req, post, timeout=timeout)
    if returnResponse:
        return response
    link = response.read()
    response.close()
    return link