from imports import *
from StringIO import StringIO
import gzip

PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/WWETV'

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 wwetv(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.TV')
        self.dnfile = 'False'
        self.currentList = 'menulist'
        self.menulist = []
        self.loading_ok = False
        self.check = 'abc'
        self.count = 0
        self.loading = 0
        self.dir()
        global old_ref
        old_ref=self.session.nav.getCurrentlyPlayingServiceReference()
        self.list_cat()

    def about(self):
        self.exit()

    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.to/','LATEST VIDEOS'),
        ('http://watchwrestling.tc/category/wwe/ppv/','WWE PPVs'),
        ('http://watchwrestling.tc/category/wwe/raw/','RAW'),
        ('http://watchwrestling.tc/category/wwe/smackdown/','Smackdown'),
        ('http://watchwrestling.tc/category/wwe/main-event/','Main Event'),
        ('http://watchwrestling.tc/category/wwe/nxt/','NXT'),
        ('http://watchwrestling.tc/category/wwe/saturday-morning-slam/','Saturday Morning Slam'),
        ('http://watchwrestling.tc/category/wwe/superstars/','Superstars'),
        ('http://watchwrestling.tc/category/wwe/totaldivas/','Total Divas'),
        ('http://watchwrestling.to/wrestlemania/','WrestleMania Collection'),
        ('http://watchwrestling.to/attitude-era/','Attitude Era'),
        ('http://watchwrestling.to/tna2/','TNA'),
        ('http://watchwrestling.to/tna2/ppv-tna/','TNA PPVs'),
        ('http://watchwrestling.to/tna2/impact-wrestling/','iMPACT Wrestling'),
        ('http://watchwrestling.to/tna2/xplosion/','Xplosion'),
        ('http://watchwrestling.to/roh/','ROH'),
        ('http://watchwrestling.to/other-sports/ufc/','UFC'),
        ('http://watchwrestling.to/other-sports/the-ultimate-fighter/','The Ultimate Fighter'),]
        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://wrestlingnetwork.tv/category/live-stream','Host':'wrestlingnetwork.tv','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:
        #cj={}
        getPage(url, timeout=12, method='GET', headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36','Cookie':'__cfduid=d19c325db0787a1811955a6fa42ef843d1485682438; bp_ut_session=%7B-q-pageviews-q-%3A1-c--q-referrer-q-%3A-q--q--c--q-landingPage-q-%3A-q-http%3A%2F%2Fwatchwrestling.tc%2Fcategory%2Fwwe%2Fraw%2F-q--c--q-started-q-%3A1485850741923%7D; _ga=GA1.2.1623757174.1485682679; _gat=1; __atuvc=5%7C5; __atuvs=589048769512c6ee000','Host':'watchwrestling.tc','Referer':'http://wrestlingnetwork.tv/'}).addCallback(self.list_shows1)

    def list_shows1(self,data): 
        print data
        #from gzip import *
        #buf = StringIO(data)
        #f = GzipFile(fileobj=buf)
        #data = f.read()

        movies=re.findall('<a class="clip-link" data-id=".*?" title=".*?" href="(.*?)">.*?<span class="clip">.*?<img src="(.*?)" alt="(.*?)"',data,re.DOTALL)
        print movies
        for each in movies:
            url,img,title = 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.tc','Referer': 'http://wrestlingnetwork.tv/category/live-stream','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('Dailymotion.*?</h2>(.*?)<h2',data,re.DOTALL)
        crypted_links_block1= re.findall('Dailymotion.*?</h2>(.*?)</center></p>',data,re.DOTALL)
        print crypted_links_block
        if crypted_links_block:
            crypted_links = re.findall('href="(.*?)">(.*?)</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)
        else:
            crypted_links= re.findall('href="(.*?)">(.*?)</a>',crypted_links_block1[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)
            

    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.tv/')
        try:
            page = urllib2.urlopen(req)
            response=page.read()
            daily_link = re.findall('src="(http://.*?)"></iframe>',response)
            if daily_link:
                print daily_link
        except:
            print 'shit - part not available'
            pass
			
        if daily_link:
            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.tv/')
            page = urllib2.urlopen(req)
            response=page.read()
            print response
            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)
        else:
            daily_link=re.findall('href="(.*?)">Full Show</a>',response)
            if daily_link:
                try:
                    page = urllib2.urlopen(req)
                    response=page.read()               
                    ln=re.findall('src="(.*?)"></iframe>',response)
                    if ln:
                        req = urllib2.Request(ln[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.tv/')
                        page = urllib2.urlopen(req)
                        response=page.read()
                        print response
                        stream720=re.findall('"720":\[\{"type":"video\\\/mp4","url":"(.*?)"',response)
                        stream480=re.findall('"480":\[\{"type":"video\\\/mp4","url":"(.*?)"',response)
                        stream380=re.findall('"380":\[\{"type":"video\\\/mp4","url":"(.*?)"',response)
                        stream240=re.findall('"240":\[\{"type":"video\\\/mp4","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)
                except:
                    pass				

    def play_that_shit(self, data):
        auswahl = self['menulist'].getCurrent()[0][0]
        self.info='player'
        sref = eServiceReference(4097, 0, data)
        sref.setName(auswahl)
        self.session.nav.playService(sref)
        self.hide()

                  

    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.tc','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',
             'Cookie': '__cfduid=d19c325db0787a1811955a6fa42ef843d1485682438; bp_ut_session=%7B-q-pageviews-q-%3A1-c--q-referrer-q-%3A-q--q--c--q-landingPage-q-%3A-q-http%3A%2F%2Fwatchwrestling.tc%2Fcategory%2Fwwe%2Fraw%2F-q--c--q-started-q-%3A1485850741923%7D; _ga=GA1.2.1623757174.1485682679; __atuvc=5%7C5; __atuvs=589048769512c6ee000'}).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/WWE/shahidSeries_poster.jpg'):
                os.system('rm -r /tmp/WWE/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()
        elif self.info=='player':
            self.show()
            self.session.nav.playService(old_ref)
            self.info='get_play_link'
            self['menulist'].l.setList(self.link_list)
            self['menulist'].l.setItemHeight(40)

    def load_poster(self):
        jp_link = self['menulist'].getCurrent()[0][2]
        tmp_image = jpg_store = '/tmp/WWE/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 = '/tmp/WWE/shahidSeries_poster.jpg'
        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 '[WWE] 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/WWE/'):
            os.system('mkdir /tmp/WWE/')
        else:
            print '[WWE] /tmp/WWE/ allready present'
			
