# -*- 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.resolvers import netu

class source:    

    def __init__(self):
        print 'GenesisFR ; INIT'
        self.base_link = 'http://full-stream.me'
        self.search_link = 'http://full-stream.me/index.php?story=%s&do=search&subaction=search'

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

    def get_sources(self, url, hosthdDict, hostDict, locDict):
        
        print 'GenesisFR ; ZMOVIE_ALTERVISTA; 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 = client.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 ; ZMOVIE_ALTERVISTA'
            
            url = 'http://zmovie.altervista.org/'
            
            #cookie = client.request(url, output='cookie')
            #post = 'action=login&login_name=ilovestreaming&login_password=ilovestreaming&Submit=&login=submit'
            #cookie = client.request(url, post=post, output='cookie')
            #result = client.request(url, cookie=cookie)
            
            j = 0

            title = title.replace(' ', '%20')
            title_english= title_english.replace(' ', '%20')
            
            #http://zmovie.altervista.org/?s=mad+max
            url = 'http://zmovie.altervista.org/?s=' + title
            
            print 'GenesisFR ; ZMOVIE_ALTERVISTA URL = %s' % url
            result = client.source(url)

            while j <= len(result) :
    
                try :
                    video_id = re.compile('movief[\"]><a href=[\"](.+?)/a>').findall(result)[j]
                    print video_id
                    video_id1 =  video_id
                    video_title = re.compile('>(.+?)<').findall(video_id)[0]
                    print video_title
                    video_id = re.compile('movief[\"]><a href=["\"](.+?)["\"]').findall(result)[j]
                    print video_id

                    video_title = video_title.replace(':', '')
                    video_title = video_title.replace('  ', ' ')
                    video_title = video_title.replace('   ', ' ')
                    video_title = video_title.replace('    ', ' ')
                    video_title = video_title.lower()
                    video_title = video_title.replace(' ', '%20')
                    print video_title

                    title = title.replace(':', '')
                    title = title.replace('  ', ' ')
                    title = title.replace('   ', ' ')
                    title = title.replace('    ', ' ')
                    #title = title.replace(' ', '')
                    print title


                    title = ud.name(unicode(title))
                    
                    

                    if (title.lower() in video_title.lower()) or (video_title.lower() in title.lower()) or (title_english.lower() in video_title.lower()) or (video_title.lower() in title_english.lower()) :
                        break
                    else :
                        j = j + 1
                        video_id = ''

                except :
                    break

            result = client.source(video_id)
            result2 = result
  
            
            
            for i in range( 1, 15) :
                
                aFlag = 0
                
                try:
                    if i == 1:
                        url = video_id
                        tempUrl1 = url
                    else:
                        tempUrl = '%d/' % i
                        url = tempUrl1 + tempUrl
                        
                        try:
                            tempResult = re.compile(url).findall(result2)[0]
                        except:
                            break
                        
                    print 'GenesisFR ; ZMOVIE_ALTERVISTA **** url %s' % url
                    result = client.source(url)
                    result2 = result
                    
                    #print ' $$$$$$$$$$$$$   result2 = %s' % result2
                    
                except :
                    pass
                    
                    
                try :
                    if aFlag == 0:
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> EASYWATCH'
                        
                        result = re.compile('<iframe src=\"(.+?)[\'|\"]').findall(result2)[0]
                        result = client.source(result)
            
                        video_id = re.compile('file:[\"](.+?)[\'|\"]').findall(result)[0]
                        label_id = re.compile('label:[\"](.+?)[\'|\"]').findall(result)[0]
            
                        url = video_id
                        url = url.encode('utf-8')
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> EASYWATCH **** url %s' % url
            
                        sources.append({'source': '(Fr) - Easywatch', 'quality': label_id, 'provider': 'ZmovieAltervista', 'url': url})
            
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> EASYWATCH **** sources %s' % sources
                        
                        aFlag = 1
                        
                        #continue
        
                except :
                    pass
                
        
        
                try :
                    if aFlag == 0:
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> ALLVID'
                        result = re.compile('<iframe src=\"(.+?)[\'|\"]').findall(result2)[0]
                        result = client.source(result)
            
                        video_id = re.compile('file:[\"](.+?)[\'|\"]').findall(result)[0]
            
                        url = video_id
                        url = url.encode('utf-8')
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> ALLVID **** url %s' % url
            
                        sources.append({'source': '(Fr) - Allvid', 'quality': 'SD', 'provider': 'ZmovieAltervista', 'url': url})
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> ALLVID **** sources %s' % sources
            
                        aFlag = 1
                        
                        #continue
        
                except :
                    pass
                
                
                
                try :
                    if aFlag == 0:
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> EXASHARE'
                        result = re.compile('<iframe src=\"(.+?)[\'|\"]').findall(result2)[0]
                        result = client.source(result)
                        
                        result = re.compile('src=[\"](.+?)[\'|\"]').findall(result)[0]
                        result = client.source(result)
                        
                        video_id = re.compile('file: [\"](.+?)[\'|\"]').findall(result)[0]
             
                        url = video_id
                        url = url.encode('utf-8')
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> EXASHARE **** url %s' % url
                        
                        sources.append({'source': '(Fr) - Exashare', 'quality': 'SD', 'provider': 'ZmovieAltervista', 'url': url})
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> EXASHARE **** sources %s' % sources
                        
                        aFlag = 1
                        
                        #continue
        
                except :
                    pass
                
                
                
                try :
                    if aFlag == 0:
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> YOUWATCH'
                        result = re.compile('<iframe src=\"(.+?)[\'|\"]').findall(result2)[0]
                        result = client.source(result)            
                        
                        video_id = re.compile('src=[\"](.+?)[\'|\"]').findall(result)[0]
                        result = client.source(video_id)
            
                        video_info = re.compile('\\|provider\\|(.+?)\\|setup').findall(result)[0]
                        video_info_split = video_info.split('|')
                        
                        video_type = video_info_split[0]
                        video_name = video_info_split[1]
                        video_ref = video_info_split[2]
                        video_port = video_info_split[3]
                        video_url_prefix = video_info_split[4]
                        
                        url = 'http://' + video_url_prefix + '.youwatch.org:' + video_port + '/' + video_ref + '/' + video_name + '.' + video_type
                        url = url.encode('utf-8')
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> YOUWATCH **** url %s' % url
            
                        sources.append({'source': '(Fr) - Youwatch', 'quality': 'SD', 'provider': 'ZmovieAltervista', 'url': url})
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> YOUWATCH **** sources %s' % sources
                        
                        aFlag = 1
                        
                        #continue
        
                except :
                    pass
                
                
        
                try :
                    if aFlag == 0:
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> SPEEDVIDEO'
                    
                        result = re.compile('<iframe src=\"(.+?)[\'|\"]').findall(result2)[0]
                        result = client.source(result)
                        
                        video_base64 = re.compile('file: base64_decode\([\"](.+?)[\)]').findall(result)[0]
                        video_base64_split = video_base64.split('\", ')
                        video_base64 = video_base64_split[0]
                        video_keyId = video_base64_split[1]
                        
                        tempLook = 'var ' + video_keyId + ' = '
                        
                        video_keyInt = int(re.compile(tempLook + '(.+?)[;]').findall(result)[0])
                        video_part_one = video_base64[:video_keyInt]
                        video_part_two = video_base64[(video_keyInt + 10):]
                        
                        video_url = video_part_one + video_part_two
                        
                        url = base64.b64decode(video_url)
                        url = url.encode('utf-8')
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> SPEEDVIDEO **** url %s' % url
                        
                        sources.append({'source': '(Fr) - Speedvideo', 'quality': 'SD', 'provider': 'ZmovieAltervista', 'url': url})
                        print 'GenesisFR ; ZMOVIE_ALTERVISTA -> SPEEDVIDEO **** sources %s' % sources
                        
                        aFlag = 1
                        
                        
                        
                        from resources.lib import resolvers

                        url = 'http://videomega.tv/cdn.php?ref=118084115056107049054081119066066119081054049107056115084118'
                        url = resolvers.request(url)
                        
                        print 'VIDEOMEGA URL = %s' % url
                        
                        sources.append({'source': '(Fr) - Videomega', 'quality': 'HD', 'provider': 'ZmovieAltervista', 'url': url})
                        
                        #continue
                
                except :
                    pass

        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