# -*- coding: utf-8 -*-
from setup import *
from imports import *
import urllib2,requests
from StringIO import StringIO
import gzip
useragent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
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 watchwrestlingup(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('watchwrestlingup')
        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.index=''
        self.count = 0
        self.loading = 0
        self.dir()
        self.onLayoutFinish.append(self.cat)

    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 cat(self):
        self.index='cat'
        self.cat_list=[]
        self.c_list=[("http://watchwrestling.uno/category/wwe/raw/","RAW"),
        ("http://watchwrestling.uno/category/wwe/smackdown/","Smackdown"),
        ("http://watchwrestling.uno/category/wwe/main-event/","Main Event"),
        ("http://watchwrestling.uno/category/wwe/nxt/","NXT"),
        ("http://watchwrestling.uno/category/wwe-total-divas/","Total Divas"),
        ("http://watchwrestling.uno/category/wwe/wwe-superstar/","Superstar"),
        ("http://watchwrestling.uno/category/wwe/wwe-ppvs/","Pay Per Views"),
        ("http://watchwrestling.uno/category/wrestlemania/","WrestleMania HD Collection"),
        ]
        for (url,title) in self.c_list:
            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_shows(self,data):
        print data
        self.index='shows'
        self.v_list=[]
        videos=re.findall('<a class="clip-link" data-id=".*?" title="(.*?)" href="(.*?)">.*?<span class="clip">.*?<img src="(.*?)"',data,re.DOTALL)
        for (title,url,img)in videos:
            self.v_list.append(show_(title,url,img))
        self['menulist'].l.setList(self.v_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)

    def get_parts(self,data):
        self.index='parts'
        self.m_list=[]	
        daily_block=re.findall('DAILYMOTION VIDEO.*?\(HD QUALITY\)</p>(.*?)<p style="text-align: center; font-size: 32px;',data,re.DOTALL)
        if daily_block:
            print daily_block #<a href="(.*?)" class="small cool-blue vision-button" target="_blank">Full Show</a>
            parts=re.findall('target="_blank">(.*?)</a><a href="(.*?)"',daily_block[0])
            if parts:
                for (part,url) in parts:
                   url='http://educadegree.com/cgi-bin/'+url
                   self.m_list.append(cat_('DAILYMOTION :'+part,url))
                self['menulist'].l.setList(self.m_list)
                self['menulist'].l.setItemHeight(40)
                self['menulist'].moveToIndex(0)
            else:
                parts=re.findall('<a href="(.*?)".*?target="_blank">(.*?)</a>',daily_block[0])
                if parts:
                    for (url,part) in parts:
                       url='http://educadegree.com/cgi-bin/'+url
                       self.m_list.append(cat_('DAILYMOTION :'+part,url))
                    self['menulist'].l.setList(self.m_list)
                    self['menulist'].l.setItemHeight(40)
                    self['menulist'].moveToIndex(0)
				
    def get_daily_q_links(self,data):
        print data
        self.index='daily'
        self.q_list=[]
        t=requests.get(data,headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36","Host":"educadegree.com","Referer":"http://watchwrestling.uno/watch-wwe-raw-21317/"},timeout=20)
        lnk=re.findall('<iframe src="(http.*?)"',t.text)
        if lnk:
            lnk=lnk[0]
            t=requests.get(lnk)
            print t.text
            q_links=re.findall('"480":\[\{"type":".*?","url":"(.*?)"\}\]',t.text)
            print q_links
            for (url) in q_links:
                url=url.replace('\\','')
                self.q_list.append(cat_('480P',url))
            q_links1=re.findall('"720":\[\{"type":".*?","url":"(.*?)"',t.text)
            for (url) in q_links1:
                url=url.replace('\\','')
                self.q_list.append(cat_('720P',url))
        self['menulist'].l.setList(self.q_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
	
    def ok(self):
        if self.index=='cat':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            print uri
            req = urllib2.Request(uri)
            req.add_header('Referer','http://watchwrestling.uno/')
            req.add_header('Upgrade-Insecure-Requests','1')
            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')
            try:
                response = urllib2.urlopen(req)
                ans = response.read()
            except:
                ans='Page changed again'
            print ans
            self.get_shows(ans)
        elif self.index=='shows':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            req = urllib2.Request(uri)
            req.add_header('Referer','http://watchwrestling.uno/')
            req.add_header('Upgrade-Insecure-Requests','1')
            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')
            print uri
            try:
                response = urllib2.urlopen(req)
                ans = response.read()
            except:
                ans='Page changed again'
            print ans

            self.get_parts(ans)
        elif self.index=='parts':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            req = urllib2.Request(uri)
            #req.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
            #req.add_header('Accept-Encoding','gzip, deflate, sdch')
            #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')
            #req.add_header('Cookie','__cfduid=dfe4f5ee9ae93c4b3dc075837ab22575c1488110945')
            #req.add_header('Host','sportsnews.pro')
            req.add_header('Referer','http://watchwrestling.uno/')
            #req.add_header('Upgrade-Insecure-Requests','1')
            req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')
            #print uri
            #try:
            response = urllib2.urlopen(req)
            #buf = StringIO(response.read())
            #f = gzip.GzipFile(fileobj=buf)
            data = response.read()
            #ans = getUrl(uri)
            #except:
            #    ans='Page changed again'
            #print ans
            self.get_daily_q_links(uri)
        elif self.index=='daily':
            uri = self['menulist'].l.getCurrentSelection()[0][1]
            print uri
            self.play_that_shit(uri)           
           

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

    def exit(self):
        if self.index=='shows':
            self.cat() 
        elif self.index=='parts':
            self.index='shows'
            self['menulist'].l.setList(self.v_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)
        elif self.index=='daily':
            self.index='parts'
            self['menulist'].l.setList(self.m_list)
            self['menulist'].l.setItemHeight(40)
            self['menulist'].moveToIndex(0)		
        elif self.index=='cat':
            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'
			
def getUrl(mainurl, cookieJar=None,post=None, timeout=20, headers=None, useproxy=True):
    global lastfinalurl
    lastfinalurl=''
    url=mainurl
    cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
    opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
    req = urllib2.Request(url)
    req.add_header('User-Agent',useragent)
    if headers:
        for h,hv in headers:
            req.add_header(h,hv)
    
    if '|' in url:
        url,header_in_page=url.split('|')
        header_in_page=header_in_page.split('&')
        
        for h in header_in_page:
            
            n,v=h.split('=')
            req.add_header(h,v)
    link=""
    try:
        response = opener.open(req,post,timeout=timeout)

        lastfinalurl = response.geturl()
        link=response.read()
        response.close()
    except: pass
    if link=="" and useproxy: 
        
        for retry in range(4):
            try:
                link=getUrlWithWebProxy(mainurl,cookieJar,post,timeout,headers)
                if not link=="": break
            except: pass
    return link;
