# -*- coding: utf-8 -*-

'''
    Genesis Add-on
    Copyright (C) 2015 lambda

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import re,urllib,urlparse,sys,unicodedata,base64

from resources.lib.libraries import cleantitle
from resources.lib.libraries import client
from resources.lib.resolvers import googleplus
from resources.lib.resolvers import openload
from resources.lib.libraries import cloudflare
from resources.lib.libraries import pyaes
from resources.lib import resolvers

class source:    

    def __init__(self):
        print 'GenesisFR ; INIT'
        self.base_link = 'http://www.vroliz.com'
        self.search_link = 'http://www.vroliz.com/'

    def get_movie(self, imdb, title, year):
        print ''

    def get_sources(self, url, hosthdDict, hostDict, locDict):
        
        print 'GenesisFR ; VROLIZ; GET_SOURCES'
        
        try :
            
            tempVOSTFR = None
            
            params = dict(urlparse.parse_qsl(sys.argv[2].replace('?','')))        

            try:
                name = params['name']
            except:
                name = None

            try:
                title = params['title']
            except:
                title = None

            try:
                year = params['year']
            except:
                year = None

            try:
                imdb = params['imdb']
            except:
                imdb = None

            title = title.lower()

            title_english = title

            url = 'http://www.imdb.com/title/%s' % imdb
            
            result = cloudflare.source(url, headers={'Accept-Language': 'fr-FR'})
            
            title = client.parseDOM(result, 'title')[0]
            title = re.compile('(.+?) [(]\d{4}[)]').findall(title)[0]
            title = title.lower()
            title = client.replaceHTMLCodes(title)
            title = title.encode('utf-8')

            aFlag = 0
            sources = []
            
        except :
            pass



        try :
            print 'GenesisFR ; VROLIZ'

            j = 0

            title = title.replace(' ', '%20')
            title_english = title_english.replace(' ', '%20')

            tempTitleList = ['ou', 'de', 'la', 'en', 'sur', 'au', 'me', 'te', 'ce', 'ces', 'que', 'a', 'pas', 'on', 'du', 'lui', 'toi', 'mes', 'le', 'un', 'une', 'aux', 'ces', 'cet', 'je', 'tu', 'il', 'elle', 'on', 'nous', 'vous', 'ils', 'elles']
            tempTitleListLen = tempTitleList.__len__()

            tempTitle = title.replace('%20', ' ')
            
            for i in range (1,tempTitleListLen ) :
                if tempTitleList[i] + ' ' in tempTitle:
                    tempTitle = tempTitle.replace(tempTitleList[i], '')

                if ' ' + tempTitleList[i] + ' ' in tempTitle:
                    tempTitle = tempTitle.replace(tempTitleList[i], '')

            tempTitle = tempTitle.lstrip()
            tempTitle = tempTitle.replace('-', ' ' )
            tempTitle = tempTitle.replace('  ', ' ' )            
            tempTitle = tempTitle.replace(' ', '+' )
            
            url = 'http://www.vroliz.com/'
            result = client.source(url)
            url = re.compile('window.location.href=\"(.+?)["\"]').findall(result)[0]
            url0 = 'http://www.vroliz.com/%s/index.php?searchword=%s&ordering=&searchphrase=all&Itemid=8&option=com_search' % (url, tempTitle[:20])
            result0 = client.source(url0)
            result1 = re.compile('<ul class=\"no-display\">(.+?)<\/span>', re.MULTILINE|re.DOTALL).findall(result0)[0]
            result2 = re.compile('<h4>(.+?)<\/h4>', re.MULTILINE|re.DOTALL).findall(result1)[0]

            title2 = title.replace('-', ' ')
            title2 = title2.lower()
            title2 = title2.replace(':', ' ')            
            title2 = title2.replace('%20', ' ')
            title2 = title2.replace('  ', ' ')
            title2 = title2.replace('  ', ' ')

            result3 = re.compile('\"  >(.+?)<font color=', re.MULTILINE|re.DOTALL).findall(result2)[0]
            url3 = re.compile('<a href=\"(.+?)\"  >', re.MULTILINE|re.DOTALL).findall(result2)[0]

            title3 = result3.lower().lstrip()
            title3 = title3.replace('-', ' ')
            title3 = title3.replace(':', ' ')
            title3 = title3.replace('%20', ' ')
            title3 = title3.replace('  ', ' ')
            title3 = title3.replace('  ', ' ')

            if title2.lower() in title3.lower() :
                
                url3 = 'http://www.vroliz.com%s' % url3
                url3 = url3.replace('&amp;', '&')
                result4 = client.source(url3)
                url5 = re.compile('proxy.link=vro\*(.+?)&autostart=').findall(result4)[0]

                key = base64.b64decode('TlluTWhIYlVkWk8wTlRCbWUxWFg=')
                dec = pyaes.Decrypter(pyaes.AESModeOfOperationECB(key + (24 - len(key)) * '\0'))
                url6 = (dec.feed(url5.decode('hex')) + dec.feed()).split('\0', 1)[0]
                url8 = resolvers.request(url6)

                if not url8 == None :
                    for i in url8:
                        sources.append({'source': 'GVideo', 'quality': i['quality'], 'provider': 'Vroliz', 'info': 'French', 'url': i['url']})
                        
                try:
                    j = 0
                    
                    result6a0 = client.source(url6)

                    while j <= len(result6a0) - 1 :
    
                        if j >= 40:
                             break
                        try:
                            url6a = ',"href":"%s#(.+?)\"}' % url6
                            url6b = re.compile(url6a).findall(result6a0)[j]

                        except:
                            break
                        
                        j = j + 1
    
                        url7a = url6 + '/#'+ url6b
                        url8 = resolvers.request(url7a)

                        if not url8 == None :
                            for i in url8:
                                sources.append({'source': 'GVideo', 'quality': i['quality'], 'provider': 'Vroliz', 'info': 'French', 'url': i['url']})
                                
                            break
                        
                except:
                
                    
                    newUrl6 = re.compile('https://picasaweb.google.com/(.+?)/').findall(url6)[0]
                    newUrl6a = 'https://picasaweb.google.com/' + newUrl6
                    newResult6 = client.source(newUrl6a)
    
                    j = 0
                    
                    while j <= len(newResult6) - 1 :
                    
                        if j >= 40:
                             break
                            
                            
                        try:
                            newresult6c = re.compile('<div><a href=\"' + newUrl6a + '(.+?)</a>', re.MULTILINE|re.DOTALL).findall(newResult6)[j]
                            newresult6d = re.compile('<p>Photos: (.+?)</p>').findall(newresult6c)[0]

                            if int(newresult6d) == 0 :
                                j = j + 1
                            else:
                                newresult6e = re.compile('<div><a href=\"(.+?)\">').findall(newResult6)[j]
                                newresult6f = client.source(newresult6e)
                                
                                try:
                                    url6a = ',"href":"%s#(.+?)\"}' % newresult6e
                                    url6b = re.compile(url6a).findall(newresult6f)[0]
                                    url7a = newresult6e + '/#'+ url6b
                                    url8 = resolvers.request(url7a)

                                    for i in url8:
                                        sources.append({'source': 'GVideo', 'quality': i['quality'], 'provider': 'Vroliz', 'info': 'French', 'url': i['url']})
                    
                                    
                                    break
                                    
                                except:
                                    break
                            
                            
                        except :
                            pass
                            
                            
                        j = j + 1
                            
        except:
            pass
            
        return sources


    def resolve(self, url):

        try:
            if url.startswith('stack://'): return url

            url = client.request(url, output='geturl')

            if 'requiressl=yes' in url: url = url.replace('http://', 'https://')

            else: url = url.replace('https://', 'http://')

            return url

        except:
            return