# -*- 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.poypi.com/rgc/'
        self.search_link = 'http://www.poypi.com/rgc/'

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

    def get_sources(self, url, hosthdDict, hostDict, locDict):
        
        print 'GenesisFR ; POYPI; 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 ; POYPI'

            j = 0

            title = title.replace(' ', '%20')
            title_english= title_english.replace(' ', '%20')
            
            url = 'http://www.poypi.com/rgc/'
            result = client.source(url)
            
            
            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(' ', '+' )
            
            title2 = title.replace('-', ' ')
            title2 = title2.lower()
            title2 = title2.replace(':', ' ')            
            title2 = title2.replace('%20', ' ')
            title2 = title2.replace('  ', ' ')
            title2 = title2.replace('  ', ' ')
            print '########## title2 = %s' % title2
            
            
            url0 = 'http://www.poypi.com/rgc/index.php?searchword=%s&ordering=&searchphrase=all&Itemid=9&option=com_search' % (tempTitle[:20])
            result0 = client.source(url0)
            
            print '########## url0 = %s' % url0
            print '########## result0 = %s' % result0
 
            result1 = re.compile('contentpaneopen["\"]>(.+?)font color=', re.MULTILINE|re.DOTALL).findall(result0)[0]
            print '########## result1 = %s' % result1
            
            result2 = re.compile('href=["\"](.+?)["\"]').findall(result1)[0]
            print '########## result2 = %s' % result2
            
            result2a = re.compile('Itemid=(.+?)<', re.MULTILINE|re.DOTALL).findall(result1)[0]
            print '########## result2a = %s' % result2a
            
            result2b = re.compile('>(.+?)\)', re.MULTILINE|re.DOTALL).findall(result2a)[0]
            print '########## result2b = %s' % result2b
            
            title3  = result2b.lower().lstrip() + ')'
            title3 = title3.replace('-', ' ')
            title3 = title3.replace(':', ' ')
            title3 = title3.replace('%20', ' ')
            title3 = title3.replace('  ', ' ')
            title3 = title3.replace('  ', ' ')
            print '########## title2 = %s        vs          title3 = %s' % (title2, title3)
            
            if title2.lower() in title3.lower():
                
                result3 = client.source('http://www.poypi.com' + result2)
                print '########## result3 = %s' % result3
                
                url3 = re.compile('proxy.link=poy\*(.+?)&autostart=').findall(result3)[0]
                print '########## url3 = %s' % url3
                
                
                key = base64.b64decode('WmdKNHlZTXg0YWlIMk5oOGZwSGg=')
                dec = pyaes.Decrypter(pyaes.AESModeOfOperationECB(key + (24 - len(key)) * '\0'))
                url6 = (dec.feed(url3.decode('hex')) + dec.feed()).split('\0', 1)[0]
    
                result6a = client.source(url6)
    
                url6a = ',"href":"%s#(.+?)\"}' % url6
                url6b = re.compile(url6a).findall(result6a)[0]
                
                while j <= len(result6a) - 1 :
                    try:
                        url6b = re.compile(url6a).findall(result6a)[j]
    
                        if len(url6b) > 0:
                            break
                        
                        j = j + 1
                        
                    except:
                        break
                        
                        
                url6b = url6 + '#' + url6b
                
                url7 = client.replaceHTMLCodes(url6b.replace('&apos;', '#'))
                url8 = resolvers.request(url7)
                
                for i in url8:
                    sources.append({'source': 'GVideo', 'quality': i['quality'], 'provider': 'Poypi', 'info': 'French', 'url': i['url']})
                        
        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