from imports import *
from StringIO import StringIO
import gzip
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 show_all_(name, link, image, info):
    res = [(name,
      link,
      image,
      info)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(800, 40), font=8, text=name, flags=RT_HALIGN_CENTER | RT_VALIGN_CENTER))
    return res


def episodes_(name, link, image, info):
    res = [(name,
      link,
      image,
      info)]
    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 wwein(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,
         'blue': self.dnitnow}, -1)
        self['menulist'] = m2list([])
        self['red'] = Label(_('Exit'))
        self['green'] = Label('')
        self['yellow'] = Label(_(' '))
        self['blue'] = Label('')
        self['Menu'] = Label(_(' '))
        self['text'] = Label('')
        self['name'] = Label('')
        self['poster'] = Pixmap()
        self['title'] = Label('WWE.IN')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        uri = 'http://watchwrestling.in/'
        self.list_cat()

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

    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]

    def up(self):
        self[self.currentList].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        if self.info == 'list_shows':
            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.info == 'list_shows':
            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.info == 'list_shows':
            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.info == 'list_shows':
            try:
                self.load_poster()
            except:
                self['text'].setText('')

    def list_cat(self):
        self.info = 'list_cat'
        self.cat_list = []
        self.cat = [('http://watchwrestling.in/sports/wwe/', 'WWE'),
         ('http://watchwrestling.in/sports/wwe-raw/', 'WWE RAW'),
         ('http://watchwrestling.in/sports/wwe-smackdown/', 'WWE SMACKDOWN'),
         ('http://watchwrestling.in/sports/wwe-main-event/', 'WWE MAIN EVENT'),
         ('http://watchwrestling.in/sports/wwe-nxt/', 'WWE NXT'),
         ('http://watchwrestling.in/sports/wwe-pay-per-view/', 'WWE PAY PER VIEW'),
         ('http://watchwrestling.in/sports/wwe-superstars/', 'WWE SUPERSTARS'),
         ('http://watchwrestling.in/sports/wwe-total-divas/', 'WWE TOTAL DIVAS'),
         ('http://watchwrestling.in/sports/tna/', 'TNA'),
         ('http://watchwrestling.in/sports/other-sport/', 'OTHER SPORT'),
         ('http://watchwrestling.in/sports/indys/', 'INDYS'),
         ('http://watchwrestling.in/sports/ufc/', 'UFC')]
        for each in self.cat:
            url, title = each
            self.cat_list.append(show_(title, url, None))

        self['menulist'].l.setList(self.cat_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        return

    def list_shows(self, data, url):
        self.info = 'list_shows'
        print data
        self.show_list = []
        max_nr = 8
        i = 1
        for i in range(1, max_nr):
            url = url + 'page/' + str(i) + '/'
            print url
            getPage(url, timeout=8, method='GET', headers={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
             'Accept-Encoding': 'gzip, deflate, sdch',
             'Accept-Language': 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4',
             'Cache-Control': 'max-age=0',
             'Connection': 'keep-alive',
             'Referer': 'http://watchwrestling.in/sports/ufc/',
             'Host': 'watchwrestling.in',
             'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'}).addCallback(self.list_shows1)
            i += 1
            url = self['menulist'].getCurrent()[0][1]
        else:
            getPage(url, timeout=8, method='GET', headers={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
             'Accept-Encoding': 'gzip, deflate, sdch',
             'Accept-Language': 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4',
             'Cache-Control': 'max-age=0',
             'Connection': 'keep-alive',
             'Host': 'watchwrestling.in',
             'Referer': 'http://watchwrestling.in/',
             '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.list_shows1)

    def list_shows1(self, data):
        buf = StringIO(data)
        f = gzip.GzipFile(fileobj=buf)
        data = f.read()
        print data
        movies = re.findall('<a class="clip-link" data-id=".*?" title="(.*?)" href="(.*?)">.*?<span class="clip">.*?<img src="(.*?)" alt="', data, re.DOTALL)
        for each in movies:
            title, url, img = each
            title = str(title).replace('Watch WWE ', '')
            if url is not '/':
                print url
                self.show_list.append(show_(title, url, img))

        self['menulist'].l.setList(self.show_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.load_poster()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)
        info = self['menulist'].getCurrent()[0][3]
        self['text'].setText(info)

    def get_play_link(self, url):
        print url
        self.info = 'get_play_link'
        getPage(url, timeout=8, method='GET', headers={'Host': 'watchwrestling.in',
         'Referer': 'http://watchwrestling.in/',
         '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.read_link, url)

    def read_link(self, data, url):
        print 'we are in get_link'
        self.link_list = []
        crypted_links_block = re.findall('<strong>Watch Dailymotion.*?</p>(.*?)<div id="extras">', data, re.DOTALL)
        print crypted_links_block
        if crypted_links_block:
            crypted_links = re.findall('<a href="(.*?)".*?-webkit-text-shadow:none">(.*?)</span></a>', crypted_links_block[0])
            print crypted_links
            for each in crypted_links:
                url, title = each
                self.link_list.append(cat_(title, url))

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

    def get_dailymotion_link(self, url):
        print 'this is url parsed to daily function : %s' % url
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
        req.add_header('Referer', 'http://watchwrestling.in/sports/wwe-raw/')
        if 'www.educationuni.com' in url:
            req.add_header('Host', 'www.educationuni.com')
        elif 'learnfree.me' in url:
            req.add_header('Host', 'learnfree.me')
        req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
        req.add_header('Accept-Language', 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4')
        req.add_header('Cache-Control', 'max-age=0')
        req.add_header('Connection', 'keep-alive')
        page = urllib2.urlopen(req)
        response = page.read()
        daily_link = re.findall('<iframe class="dailymotion".*?src="(.*?)"', response)
        print daily_link
        if daily_link:
            print daily_link[0]
            req = urllib2.Request(daily_link[0])
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
            req.add_header('Referer', 'http://watchwrestling.in/home/')
            page = urllib2.urlopen(req)
            response = page.read()
            print response
            if 'title":"Inhalt abgelehnt."' in response:
                self.session.open(MessageBox, _('Video wurde geloescht'), MessageBox.TYPE_INFO, timeout=3)
            else:#"720":[{"type":"application\/x-mpegURL","url":"http:\/\/www.dailymotion.com\/cdn\/manifest\/video\/x514qdt.m3u8?auth=1478980288-2688-fqc5uj94-8538425606bcd87581083effd85f7c1e&include=720"},
                stream720 = re.findall('"720":\[\{"type":".*?","url":"(.*?)"\},', response)
                stream480 = re.findall('"480":\[\{"type":".*?","url":"(.*?)"\},', response)
                stream380 = re.findall('"380":\[\{"type":".*?","url":"(.*?)"\},', response)
                stream240 = re.findall('"240":\[\{"type":".*?","url":"(.*?)"\},', response)
                if stream720:
                    final_url = str(stream720[0]).replace('\\', '')
                    self.play_that_shit(final_url)
                elif stream480:
                    final_url = str(stream480[0]).replace('\\', '')
                    self.play_that_shit(final_url)

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

    def ok(self):
        if self.info == 'list_cat':
            selectedEntry = self['menulist'].l.getCurrentSelection()[0][1]
            selectedName = self['menulist'].l.getCurrentSelection()[0][0]
            print selectedEntry
            url = str(selectedEntry)
            getPage(url, timeout=8, method='GET', headers={'Host': 'watchwrestling.in',
             'Referer': 'http://watchwrestling.in/',
             '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.list_shows, url)
        elif self.info == 'list_shows':
            selectedEntry = self['menulist'].getCurrent()[0][1]
            selectedName = self['menulist'].getCurrent()[0][0]
            url = selectedEntry
            self.filmname = str(selectedName)
            self.get_play_link(url)
        elif self.info == 'get_play_link':
            selectedEntry = self['menulist'].getCurrent()[0][1]
            self.get_dailymotion_link(selectedEntry)

    def exit(self):
        print self.info
        if re.match('(list_cat)', self.info, re.S | re.I):
            if fileExists('/tmp/shahidSeries_poster.jpg'):
                os.system('rm -r /tmp/shahidSeries_poster.jpg')
            self.close(self.session, 'exit')
        elif self.info == 'list_shows':
            self.info = 'list_cat'
            self['blue'].hide()
            self['menulist'].l.setList(self.cat_list)
            self['menulist'].l.setItemHeight(40)
        elif self.info == 'get_play_link':
            self.info = 'list_shows'
            self['blue'].hide()
            self['menulist'].l.setList(self.show_list)
            self['menulist'].l.setItemHeight(40)
            self.load_poster()

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

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