# -*- 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,os,datetime,time,webbrowser,sys,xbmc,base64
from resources.lib.pyperclip import pyperclip
from resources.lib.libraries import control
from resources.lib.indexers import movies
from resources.lib.indexers import tvshows
from resources.lib.indexers import episodes

try: voiceListenTimeout = int(control.setting('voice_timeout_10'))
except: voiceListenTimeout = 10

try: commandsTimeout = int(control.setting('commands_timeout_3'))
except: commandsTimeout = 3

try: voiceEnabled = control.setting('voiceOnOff')
except: voiceEnabled = 'false'
        
def voiceRecognition():
    try:
        #https://translate.google.com/#fr/en/hi%20my%20name%20is%20R%C3%A9gis
        
        #Operative system   File path
        #Android            Android/data/org.xbmc.kodi/files/.kodi/userdata/ (see note)
        #iOS                /private/var/mobile/Library/Preferences/Kodi/userdata/
        #Linux              ~/.kodi/userdata/
        #Mac                /Users/<your_user_name>/Library/Application Support/Kodi/userdata/ (see note)
        #OpenELEC           /storage/.kodi/userdata/
        #Windows Start - type %APPDATA%\kodi\userdata - press <Enter>
        



        print 'CHROME 5'
        
        movieOrTV = None
        tempTheSearch = None
        theCommand = ''
        thequery = None
        newquery = None
        lang_menu_list = None
        googleCmd = None

        lang_menu_list = []


        print 'CHROME 55555555'

        if voiceEnabled == 'true' :
            if 'win32' in sys.platform:
                from resources.lib.libraries import SendKeys
                
                #webbrowser.get('google-chrome').open_new('https://example.com')
            
                os.system('taskkill /im chrome.exe')
                os.system('start chrome \"https://www.google.com/\"')
                print 'WindowsPlatform 4'
            
                time.sleep(voiceListenTimeout)
                SendKeys.SendKeys('^+.')
                print 'WindowsPlatform 5'
                
                time.sleep(commandsTimeout)
                SendKeys.SendKeys('^l')
                
                time.sleep(commandsTimeout)
                SendKeys.SendKeys('^c')
                
                time.sleep(commandsTimeout)
                SendKeys.SendKeys('^w')
                
                #time.sleep(commandsTimeout)
                #SendKeys.SendKeys('^m')
    
            elif 'linux' in sys.platform:
                print 'UnixPlatform'
            elif 'darwin' in sys.platform:
                # gotta be a better way to detect ipad/iphone/atv2
                if 'USER' in os.environ and os.environ['USER'] in ('mobile','frontrow',):
                    print 'IOSPlatform'
                else: 
                    print 'MacPlatform'
    
                    url = 'http://www.google.com/'
                    chrome_path = 'open -a /Applications/Google\ Chrome.app %s'
                    webbrowser.get(chrome_path).open(url)
                    
                    time.sleep(voiceListenTimeout)
    
                    #os.system('afplay /System/Library/Sounds/Sosumi.aiff')
                    #os.system('afplay /System/Library/Sounds/Sosumi.aiff')
    
                    #invoke microphone
                    cmd = """
                        osascript -e 'tell application "System Events" to keystroke "." using {command down, shift down}'
                        """                
                    # minimize active window
                    os.system(cmd)
                    
                    time.sleep(voiceListenTimeout)
                    
                    #Highlight url
                    cmd = """
                        osascript -e 'tell application "System Events" to keystroke "l" using {command down}'
                        """
                    # minimize active window
                    os.system(cmd)
                    
                    time.sleep(commandsTimeout)
                    
                    #Copy url in clipboard
                    cmd = """
                        osascript -e 'tell application "System Events" to keystroke "c" using {command down}'
                        """                
                    # minimize active window
                    os.system(cmd)
                    
                    time.sleep(commandsTimeout)
                    
                    #Copy url in clipboard
                    cmd = """
                        osascript -e 'tell application "System Events" to keystroke "w" using {command down}'
                        """                
                    # minimize active window
                    os.system(cmd)
                    
                    time.sleep(commandsTimeout)
                    
                    #Copy url in clipboard
                    cmd = """
                        osascript -e 'tell application "System Events" to keystroke "m" using {command down}'
                        """                
                    # minimize active window
                    os.system(cmd)
                    
                    time.sleep(commandsTimeout)
    
                    #Copy url in clipboard
                    cmd = """
                        osascript -e 'tell application "System Events" to keystroke "q" using {command down}'
                        """                
                    # minimize active window
                    os.system(cmd)
    
                    #os.system('afplay /System/Library/Sounds/Sosumi.aiff')
                    #os.system('afplay /System/Library/Sounds/Sosumi.aiff')
                    #os.system('afplay /System/Library/Sounds/Sosumi.aiff')
            
            googleCmd = pyperclip.paste() #get url from clipboard
            
            print '## googleCmd ## %s' % googleCmd
            
            try:
                googleCmd = re.compile('q=(.+?)$').findall(googleCmd)[0]
                googleCmd = googleCmd.replace('&tts=0', '')
            except:
                pass
    
            thequery = googleCmd
            #thequery = 'Movie+Genre' ###########googleCmd
            #thequery = 'Movie+Year'
            #thequery = 'Movie+People'
            #thequery = 'Movie+Featured'
            #thequery = 'Movie+People+Watching'
            #thequery = 'Movie+Most+Popular'
            #thequery = 'Movie+Most+Voted'
            #thequery = 'Movie+Box+Office'
            #thequery = 'Movie+Oscar+Winners'
            #thequery = 'Movie+In+Theaters'
            #thequery = 'Movie+Latest+Movies'
            #thequery = 'Movie+Favourites'
            #####thequery = 'Movie+Search+American+Snipper'
            
            
            
            
            #thequery = 'TV+Shows+Genres'
            #thequery = 'TV+Shows+Year'
            #thequery = 'TV+Shows+Network'
            #thequery = 'TV+Shows+People+Watching'
            #thequery = 'TV+Shows+Popular'
            #thequery = 'TV Shows+Airing+today'
            #thequery = 'TV+Shows+New+TV+Shows'
            #thequery = 'TV+Shows+Returning+TV+Shows'
            #thequery = 'TV+Shows+Highly+Rated'
            #thequery = 'TV+Shows+Most+Voted'
            #thequery = 'TV+Shows+TV+Calendar'
            #thequery = 'TV Shows+Latest+Episodes'
            ####thequery = 'TV Shows+Faourites'
            #####thequery = 'TV Shows+Faourites+Episodes'
            
            
            
            
            
    
            #newquery = thequery
    
            thequery = thequery.encode('utf-8').lower().replace('+', ' ').split(' ')
            #newquery = newquery.encode('utf-8').lower().replace('+', ' ').split(' ')
            
            #tempTheSearch = ''
    
    
            if thequery[0] in control.lang(30001).encode('utf-8').lower():
                movieOrTV = 'Movie'
                del thequery[0]
    
            if thequery[0] in control.lang(30002).encode('utf-8').lower():
                movieOrTV = 'TV'
                del thequery[0]
                del thequery[0]
    
            #Search
            #if thequery[0] in control.lang(30009).encode('utf-8').lower():
            #    tempTheSearch = 30009
            #    del newquery[0]
            #    del newquery[0]
    
            #People Search
            #elif thequery[1] in control.lang(30034).encode('utf-8').lower():
            #    tempTheSearch = 300034
            #    del newquery[0]
            #    del newquery[0]
            #    del newquery[0]
    
    
    
            #tempTitle = ' '.join(newquery)
    
    
            #print 'WWWWWWW  %s        %s' % (tempTheSearch, newquery)
    
            if movieOrTV == 'Movie' :
                for i in range(30000, 30045):
                    try:
                        menuesItems = control.lang(i).encode('utf-8').lower()
    
                        deepLevel = thequery.__len__()
                                
                        if deepLevel == 1 and (thequery[0] in menuesItems):
                            lang_menu_list.append([i,control.lang(i).encode('utf-8').lower(), True])
                            print '########## LEVEL 1 ... MOVIE ....  MATCH FOR .... %s ' % thequery[0]
                            print '.   '
                            del thequery[0]
                            break
                
                        if deepLevel == 2 and (thequery[0] + ' ' + thequery[1] in menuesItems):
                            lang_menu_list.append([i,control.lang(i).encode('utf-8').lower(), True])
                            print '########## LEVEL 2 ... MOVIE ....  MATCH FOR .... %s ' % (thequery[0] + ' ' + thequery[1])
                            print '.   '
                            del thequery[0]
                            del thequery[0]
                            break
                        
                        if deepLevel == 3 and (thequery[0] + ' ' + thequery[1] + ' ' + thequery[2] in menuesItems) :
                            lang_menu_list.append([i,control.lang(i).encode('utf-8').lower(), True])
                            print '########## LEVEL 3 ... MOVIE ....  MATCH FOR .... %s ' % (thequery[0] + ' ' + thequery[1] + ' ' + thequery[2])
                            print '.   '
                            del thequery[0]
                            del thequery[0]
                            del thequery[0]
                            break
                                
                        if deepLevel >= 4 and (thequery[0] + ' ' + thequery[1] + ' ' + thequery[2] + ' ' + thequery[3] in menuesItems):
                            lang_menu_list.append([i,control.lang(i).encode('utf-8').lower(), True])
                            print '########## LEVEL 4 ... MOVIE ....  MATCH FOR .... %s ' % (thequery[0] + ' ' + thequery[1] + ' ' + thequery[2] + ' ' + thequery[3])
                            print '.   '
                            del thequery[0]
                            del thequery[0]
                            del thequery[0]
                            del thequery[0]
                            break
    
                    except:
                        pass
                    
                    
            if movieOrTV == 'TV' :
                for i in range(30046, 30070):
                    try:
                        menuesItems = control.lang(i).encode('utf-8').lower()
                        
                        print menuesItems
                        
                        print '@@    ' + thequery[0]
                        
                        deepLevel = thequery.__len__()
                        
                        if deepLevel == 1 and (thequery[0] in menuesItems):
                            lang_menu_list.append([i,control.lang(i).encode('utf-8').lower(), True])
                            print '########## LEVEL 1 ... TV ....  MATCH FOR .... %s ' % thequery[0]
                            print '.   '
                            del thequery[0]
                            break
                        
                        if deepLevel == 2 and (thequery[0] + ' ' + thequery[1] in menuesItems):
                            lang_menu_list.append([i,control.lang(i).encode('utf-8').lower(), True])
                            print '########## LEVEL 2 ... TV ....  MATCH FOR .... %s ' % (thequery[0] + ' ' + thequery[1])
                            print '.   '
                            del thequery[0]
                            del thequery[0]
                            break
                        
                        if deepLevel == 3 and (thequery[0] + ' ' + thequery[1] + ' ' + thequery[2] in menuesItems) :
                            lang_menu_list.append([i,control.lang(i).encode('utf-8').lower(), True])
                            print '########## LEVEL 3 ... TV ....  MATCH FOR .... %s ' % (thequery[0] + ' ' + thequery[1] + ' ' + thequery[2])
                            print '.   '
                            del thequery[0]
                            del thequery[0]
                            del thequery[0]
                            break
                        
                        if deepLevel >= 4 and (thequery[0] + ' ' + thequery[1] + ' ' + thequery[2] + ' ' + thequery[3] in menuesItems):
                            lang_menu_list.append([i,control.lang(i).encode('utf-8').lower(), True])
                            print '########## LEVEL 4 ... TV ....  MATCH FOR .... %s ' % (thequery[0] + ' ' + thequery[1] + ' ' + thequery[2] + ' ' + thequery[3])
                            print '.   '
                            del thequery[0]
                            del thequery[0]
                            del thequery[0]
                            del thequery[0]
                            break
                
                    except:
                        pass
    
    
            print '########### %s'  % lang_menu_list
            
            
            
            for j in range(0, len(lang_menu_list)) :
                print 'lang_menu_list =========   %s' % lang_menu_list[j][0]
                theCommand = theCommand + ' ' + str(lang_menu_list[j][0])
                print 'theCommand = %s' % theCommand
    
            print 'THECOMMAND %s' % theCommand
            
            
            
            
            ###############################################################
            # M O V I E S
            ###############################################################
            
            print 'MOVIE movieOrTV = %s' % movieOrTV
            
            if movieOrTV == 'Movie' :
                #Movies...Genres
                if str(30021) in theCommand :
                    movies.movies().genres()
                
                #Movies...Genres
                #if str(30021) in theCommand :
                #    movies.movies().genresVoice(thequery2)
                
                #Movies...Years
                if str(30022) in theCommand :
                    movies.movies().years()
                    
                #Movies...People
                if str(30023) in theCommand :
                    movies.movies().persons()
                    
                #Movies...Certificate
                if str(30024) in theCommand :
                    movies.movies().certifications()
                
                #Movies...Featured
                if str(30025) in theCommand :
                    movies.movies().get('featured')
                    
                #Movies ...People Watching
                if str(30026) in theCommand :
                    trending_link = 'http://api-v2launch.trakt.tv/movies/trending?limit=200&page=1'
                    movies.movies().get(trending_link)
                
                #Movies ...Popular
                if str(30027) in theCommand :
                    movies.movies().get('popular')
                
                #Movies ...Most Voted
                if str(30028) in theCommand :
                    movies.movies().get('views')
                    
                #Movies ...Box Office
                if str(30029) in theCommand :
                    movies.movies().get('boxoffice')
                    
                #Movies ...Oscars
                if str(30030) in theCommand :
                    movies.movies().get('oscars')
                
                #Movies ...Theaters
                if str(30031) in theCommand :
                    movies.movies().get('theaters')
    
                #Movies ...Latest Movies
                if (str(30005) or str(30032)) in theCommand :
                    movies.movies().get('added')
            
                #Movies ...Favourites
                if str(30033) in theCommand :
                    movies.movies().favourites()
    
                #Movies ...Search
                #if tempTheSearch == 30009 :
                #    print 'TEST...................   30009'
                #    movies.movies().search(tempTitle)
    
                #Movies ...People Search
                #if str(30034) in theCommand :
                    #print 'MMMMMMMMMMMMM     %s' % thequery
                    #movies.movies().person(thequery2)
            
    
    
    
    
    
            ###############################################################
            # TV  S H O W S
            ###############################################################
            print 'TV movieOrTV = %s' % movieOrTV
            
            if movieOrTV == 'TV' :
                #TV Shows...Genres...OK
                if str(30051) in theCommand :
                    tvshows.tvshows().genres()
                    
                #TV Shows...Years...OK
                if str(30052) in theCommand :
                    tvshows.tvshows().years()
                    
                #TV Shows...Networks...OK
                if str(30053) in theCommand :
                    tvshows.tvshows().networks()
                    
                #TV Shows ...People Watching...OK
                if str(30054) in theCommand :
                    trending_link = 'http://api-v2launch.trakt.tv/shows/trending?limit=200&page=1'
                    tvshows.tvshows().get(trending_link)
                
                #TV Shows ...Most Popular...OK
                if str(30055) in theCommand :
                    tvshows.tvshows().get('popular')
                
                #TV Shows...Airing today...OK
                if str(30056) in theCommand :
                    tvshows.tvshows().get('airing')
    
                #TV Shows ...New TV Shows
                if str(30058) in theCommand :
                    tvshows.tvshows().get('premiere')
                
                #TV Shows...Returning TV Shows...OK
                if str(30057) in theCommand :
                    tvshows.tvshows().get('active')
                
                #TV Shows...Highly rated...
                if str(30059) in theCommand :
                    tvshows.tvshows().get('rating')
                
                #TV Shows...Most Voted...
                if str(30060) in theCommand :
                    tvshows.tvshows().get('views')
                
                #TV Shows...TV Calendar...
                if str(30061) in theCommand :
                    episodes.episodes().calendars()
                
                #TV Shows...Latest Episodes...
                if str(30062) in theCommand :
                    episodes.episodes().widget()
                
                #TV Shows...Faourites...Episodes
                if str(30063) in theCommand :
                    episodes.episodes().favourites()
    
            return None
    except:
        return None
    
    
    

