from imports import *
from VirtualKeyBoard import VirtualKeyBoard
PLUGIN_PATH = '/usr/lib/enigma2/python/Plugins/Extensions/Albatros'
fav_file='/usr/lib/enigma2/python/Plugins/Extensions/Albatros/fav_daily'

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

    def __init__(self, session):
        Screen.__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
        self['red'] = Label(_('Exit'))
        self['green'] = Label('Search')
        self['yellow'] = Label(('Add2Fav'))
        self['blue'] = Label('OpenFav')
        self['Menu'] = Label(_(' '))
        self['text'] = Label('')
        self['name'] = Label(' ')
        self['poster'] = Pixmap()
        self['title'] = Label('Dailymotion')
        self['menulist'] = m2list([])
        self.onLayoutFinish.append(self.get_clips)
        self['shortcuts'] = NumberActionMap(['ShortcutActions',
         'WizardActions',
         'NumberActions',
         'InputActions',
         'InputAsciiActions',
         'KeyboardInputActions'], {'up': self.up,
         'down': self.down,
         'left': self.left,
         'right': self.right}, -1)
        self['OkCancelActions'] = HelpableActionMap(self, 'OkCancelActions', {'cancel': self.exit,
         'ok': self.ok}, -1)
        self['ColorActions'] = HelpableActionMap(self, 'ColorActions', {'red': self.exit,
         'blue': self.openfav,
         'yellow' : self.addtofav,
         'green': self.search}, -1)
        self['EPGSelectActions'] = HelpableActionMap(self, 'EPGSelectActions', {'nextBouquet': self.b_up,
         'prevBouquet': self.b_down}, -1)

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

    def addtofav(self):
        title = self['menulist'].l.getCurrentSelection()[0][0]
        url = self['menulist'].l.getCurrentSelection()[0][1]
        f = open(fav_file,'a+')
        f.write('title:'+title+';url='+url+'end')
        f.close()     
	
    def openfav(self):
        with open(fav_file, "r") as ins:
            array = []
            for line in ins:
                array.append(line)
            print array
        self.index = 'list_series'
        self.series_list = []
        ser=re.findall('title:(.*?);url=(.*?)end',str(array))
        for title,url in ser:
            self.series_list.append(cat_(title, url))
        self['menulist'].l.setList(self.series_list)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def b_up(self):
        self['menulist'].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def up(self):
        self['menulist'].up()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def b_down(self):
        self['menulist'].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def down(self):
        self['menulist'].down()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def left(self):
        self['menulist'].pageUp()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def right(self):
        self['menulist'].pageDown()
        auswahl = self['menulist'].getCurrent()[0][0]
        self['name'].setText(auswahl)

    def exit(self):
        self.close()

    def search(self):
        self.session.openWithCallback(self.searchDaily, VirtualKeyBoard, title=_('Enter name of the show'))

    def searchDaily(self, searchstring = None):
        self.search_list = []
        if searchstring:
            searchstring_fin = searchstring.replace(' ', '+')
            print searchstring_fin
            url = 'http://www.dailymotion.com/de/relevance/universal/search/' + searchstring_fin
            max_nr=8
            i = 1
            for i in range(1, max_nr):
                url = url + '/' + str(i)
                #print url
                getPage(url, timeout=15, headers={'Host':'www.dailymotion.com','Content-Type': 'application/x-www-form-urlencoded'}).addCallback(self.search_data)
                i += 1
                url = 'http://www.dailymotion.com/de/relevance/universal/search/' + searchstring_fin
			

    def search_data(self, data):
        self.index = 'search'
        movies=re.findall('href="(.*?)" class="link js-track" title="(.*?)" data-context="', data)
        #movies = re.findall('href="(.*?)" data-context=".*?"  data-xid=".*?">.*?alt="(.*?)" title="', data, re.DOTALL)
        print movies
        for each in movies:
            url, title = each
            url = 'http://www.dailymotion.com' + url
            print title
            if 'title' not in title:
                self.search_list.append(show_(title, url, None))

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

    def listPlugins(self):
        self.index = '1'
        self.pluginlist = []
        self.pluginlist.append(show_('Dailymotion', 'http://www.dailymotion.com/de', None))
        self['menulist'].l.setList(self.pluginlist)
        self['menulist'].l.setItemHeight(40)
        self['menulist'].moveToIndex(0)
        self.countplugins = len(self.pluginlist)
        self['info'].setText('Sections: found: %s sections.' % self.countplugins)
        return

    def ok(self):
        url = self['menulist'].getCurrent()[0][1]
        print url
        if self.index == '1':
            self.get_clips(url)
        if self.index == '2':
            print url
            self.get_crypted_links(url)
        elif self.index == 'search':
            print url
            self.get_crypted_links(url)

    def get_clips(self):
        url = 'http://www.dailymotion.com/de'
        self.index = '2'
        self.clip_list = []
        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://www.dailymotion.com/de')
        page = urllib2.urlopen(req)
        response = page.read()
        clips = re.findall('<a class="link" href="http://www.dailymotion.com/video/(.*?)".*?title="(.*?)"', response)
        print clips
        for each in clips:
            url, title = each
            title = title.replace('#039;', '').replace('&amp;', '').replace('&de', '')
            url = 'http://www.dailymotion.com/embed/video/' + url + '?syndication=114459?logo=0&autoPlay=1&quality=480'
            self.clip_list.append(show_(title, url, None))

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

    def get_crypted_links(self, url):
        print url
        if 'http://www.dailymotion.com/video/' in url:
            url = url.replace('video', 'embed/video')
            print 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://www.dailymotion.com/de')
        page = urllib2.urlopen(req)
        response = page.read()
        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)
        else:
            final_url = str(stream480[0]).replace('\\', '')
            self.play_that_shit(final_url)

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