#!/usr/env/python3
# coding: utf-8
# la ligne coding ci-dessus permet d'éviter les erreurs d'accents
# https://openclassrooms.com/forum/sujet/quot-syntaxerror-non-ascii-character-xc3-in-filequot-12536

import speech_recognition as sr
import os

# This script was written by Greg Colburn (ThePony on github). Feel free
# to contact me on FB at https://www.facebook.com/9millionthGreg BUT...
# when contacting me please be sure to tell my WHY you are messaging me!
# donations to keep snacks on hand for my coding spurts are welcome at
# paypal at (colburn greg at.symbol.goes.here ya hoo dot com), thanks

# https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# evite les erreurs du type
# UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)

r = sr.Recognizer()
m = sr.Microphone()

# anciennes variables
lampe_fr = ['leave me alone', 'Lumia', 'meet me on', 'read me out', 'Romeo', 'Romania', 'rythmia', 'wake me up']
television_en = ['television']

# nouvelle variable unique a utiliser par la suite
# action 'browser' necessite 'site'
cle = {
    'exitWord': {
        'action' : 'main_pgm' ,
        'mots'   : ['quitter', 'Quitterie']
        },

    'REBOOTER': {
        'action' : 'exec' ,
        'command': 'sudo',
        'args'   : ['reboot'],
        'mots'   : ['redémarrer la machine']
        },

    'EDITION' : {
        'action' : 'exec' ,
        'command': 'geany',
        'args'   : ['/home/pi/Documents/piTalk-master/talking.py'],
        'mots'   : ['édition programme']
        },

    'SAUVEGARDE' : {
        'action' : 'exec' ,
        'command': '/home/pi/Documents/piTalk-master/sauvegarde.sh',
        'args'   : [''],
        'mots'   : ['sauvegarde programme']
        },




    'tmp_foot': {
        'action' : 'browser' ,
        'site'   : 'http://gangand.net/ss/sport_euro_2021/i2.php?cpt=foot/euro_2021',
        'mots'   : ['sport', 'foot', 'football', 'championnat d\'Europe', 'champion d\'Europe']
        },

    'corona': {
        'action' : 'browser' ,
        'site'   : 'http://gangand.net/cc/coro/stats/index.php?device=PC',
        'mots'   : ['Corona', 'corona']
        },

    'domotique' : {
        'action' : 'gpio_domotique' ,
        'mots'   : ['boutique', 'domotique']
        },

    # fichiers
    'fichier_achats_fournitures' : {
        'action' : 'exec' ,
        'command': 's3f',
        'args'   : ['achats', 'fournitures'],
        'mots'   : ['leroy merlin', 'fourniture', 'achats fournitures', 'achat fournitures']
        },

    'fichier' : {
        'action' : 'recherche_fichier' ,
        'command': 's3f',
        'args'   : [''],
        'mots'   : ['chercher fichier', 'recherche pied']
        },

    # radios web
    'france_inter' : {
        'action' : 'exec' ,
        'command': 'vlc',
        'args'   : ['http://direct.franceinter.fr/live/franceinter-midfi.mp3'],
        'mots'   : ['inter', 'france inter', 'France Inter']
        },

    'jeux': {
        'action' : 'exec' ,
        'command': 'pysolfc',
        'mots'   : ['jeu', 'jeux', 'jeu du solitaire'],
        'args'   : ''
        },

    'internet': {
        'action' : 'browser' ,
        'site'   : 'http://gangand.net',
        'mots'   : ['internet']
        },

    'libreoffice': {
        'action' : 'exec' ,
        'command': 'libreoffice',
        'mots'   : ['libre', 'libreoffice']
        },

    'lampe_fr': {
        'action' : 'gpio_domotique' ,
        'mots'   : ['allume la lampe']
        },

    'meteo': {
        'action' : 'browser' ,
        'site'   : 'https://www.google.com/search?q=meteo+reims',
        'mots'   : ['quel temps', 'météo']
        },

    'navigateur_fermer_onglet' : {
        'action' : 'exec' ,
        'command': 'mav_xdotool.sh',    # fichier mav_xdotool.sh à créer
                                        # mav = mon assistant vocal
        'args'   : ['fermer_onglet'],
        'mots'   : ['fermer onglet']
        },

    'musique' : {
        'action' : 'exec' ,
        'command': 'vlc',
        # 'args'   : ['/media/fbx/xavbox/type1/', '>/dev/null', '2>&1'],
        'args'   : ['/media/fbx/xavbox/type1/'],
        'mots'   : ['boutique', 'musique']
        },

    'musique_off' : {
        'action' : 'exec' ,
        'command': 'killall',
        'args'   : ['vlc'],
        'mots'   : ['arrête la musique', 'arrêter la musique', 'arrêter musique', 'arrête musique']
        },

    'television_en' : {
        'action' : 'exec' ,
        'command': 'vlc ',
        'args'   : ['http://gangand.net/tt/tv/free_sd.m3u'],
        'mots'   : ['Billy', 'CD', 'DD', 'Siri', 'television']
        },

}

# commandes spéciales concernant le pgm même
exitWord  = cle['exitWord'  ]['mots']
REBOOTER  = cle['REBOOTER'  ]['mots']
EDITION   = cle['EDITION'   ]['mots']
SAUVEGARDE= cle['SAUVEGARDE']['mots']


# temporaire
tmp_foot  = cle['tmp_foot']['mots']

# commandes vocales
corona      = cle['corona'      ]['mots']
domotique   = cle['domotique'   ]['mots']
internet    = cle['internet'    ]['mots']
jeux        = cle['jeux'        ]['mots']
libreoffice = cle['libreoffice' ]['mots']
meteo       = cle['meteo'       ]['mots']
# ~ radio        = cle['radio']['mots']
france_inter = cle['france_inter']['mots']
# ~ france_info  = cle['radios']['france_info' ]['mots']
musique     = cle['musique'     ]['mots']
musique_off = cle['musique_off' ]['mots']


print("*" * 50)
for i, j in enumerate(cle):
    print("%15s : %s" % (j, cle[j]['mots']) )
print("*" * 50)
print()


# Voir aussi
# https://stackoverflow.com/questions/36244380/enumerate-for-dictionary-in-pythonw
# for index, (key, value) in enumerate(your_dict.items()):
    # print(index, key, value)

import subprocess

# def date_heure():
    # from datetime import datetime
    # from time import strftime
    # return strftime('%Y-%m-%d %H:%M:%S', datetime.now())

def date_heure():
    # https://waytolearnx.com/2020/06/date-et-heure-en-python.html
    from datetime import datetime
    t = datetime.now()
    # return str(t.year) + ' ' + str(t.month) + ' ' + str(t.hour) + ' ' + str(t.minute) + ' ' + str(t.second)
    # https://docs.python.org/fr/3.5/library/string.html
    # https://stackoverflow.com/questions/339007/how-to-pad-zeroes-to-a-string
    return '{0}-{1:02d}-{2:02d}-{3:02d}-{4:02d}'.format(t.year, t.month, t.hour, t.minute, t.second)

def lancement_original():
    try:
        print("One moment...")
        with m as source: r.adjust_for_ambient_noise(source)
        # The above line takes an ambient sample of noise to set threshhold levels.
        # This may not work on all microphones and should be tweaked as needed
        while True:
            # print("Now Ready, talk to me. (Press Ctrl+c to or say exit or quit to quit)")
            print("Prêt, veuillez parler. (Presser Ctrl+c ou dire quitter pour quitter)")
            with m as source: audio = r.listen(source)
            print(".")
            try:
                # ~ value = r.recognize_google(audio)
                value = r.recognize_google(audio, language="fr-FR")
                # passer en francais
                # https://stackoverflow.com/questions/49732536/how-to-change-the-language-of-google-speech-recognition

                if str is bytes:
                    reply = "{}".format(value).encode("utf-8")
                else:
                    reply = "{}".format(value)
                print("reply = %s " % reply)

                if reply in exitWord:
                    quit()

                elif reply in jeux:             # game anglais
                    print(date_heure(), "jeux")
                    # subprocess.Popen( ['pysolfc', '']).pid
                    tableau = []
                    tableau.append(cle['jeux']['command'])
                    for i in cle['jeux']['args']:
                        tableau.append(i)
                    subprocess.Popen( list(tableau) ).pid


                elif reply in internet:      # internet
                    print(date_heure(), "internet %s" % reply)
                    print("Lancement de chromium-browser http://gangand.net")
                    subprocess.Popen( ['chromium-browser', 'http://gangand.net']).pid

                elif reply in lampe_fr:     # lumiere fr
                    print("lampe_fr %s" % reply)
                    subprocess.Popen( ['chromium-browser', 'https://www.google.com/search?q=domotique+lampe']).pid

                elif reply in meteo:         # meteo fr
                    print(date_heure(), "meteo %s" % reply)
                    # print("Lancement de chromium-browser https://www.google.com/search?q=meteo+reims")
                    # subprocess.Popen( ['chromium-browser', 'https://www.google.com/search?q=meteo+reims']).pid

                    # print("meteo")
                    # subprocess.Popen( ['chromium-browser', 'http://gangand.net/cc/coro/stats/index.php?device=PC']).pid

                    tableau = []
                    choix = cle['meteo']
                    if ( choix['action'] == 'browser' ):
                            subprocess.Popen( ['chromium-browser', choix['site'] ] ).pid
                    else:
                            tableau.append(r['command'])
                            for i in r['args']:
                                tableau.append(i)
                            subprocess.Popen( list(tableau) ).pid

                elif reply in tmp_foot:
                    print(date_heure(), "tmp_foot %s" % reply)
                    tableau = []
                    choix = cle['tmp_foot']
                    if ( choix['action'] == 'browser' ):
                            subprocess.Popen( ['chromium-browser', choix['site'] ] ).pid
                    else:
                            tableau.append(r['command'])
                            for i in r['args']:
                                tableau.append(i)
                            subprocess.Popen( list(tableau) ).pid

                elif reply in musique:         # music fr
                    print("musique %s" % reply)
                    print("Utiliser exit pour quitter l'assistant vocal sans killer vlc (Ctrl-C le kille)")
                    # commande initiale brute
                    # ~ subprocess.Popen( ['vlc', '/media/fbx/xavbox/type1/', '>/dev/null', '2>&1']).pid


                    # --------------------------------------
                    # OK CI DESSOUS
                    # ~ tableau = []
                    # ~ tableau.append(cle['musique']['command'])
                    # ~ for i in cle['musique']['args']:
                        # ~ tableau.append(i)
                    # ~ subprocess.Popen( list(tableau) ).pid
                    # --------------------------------------
                    tableau = []
                    tableau.append(cle['musique']['command'])
                    for i in cle['musique']['args']:
                        tableau.append(i)
                    subprocess.Popen( list(tableau) ).pid

                elif reply in musique_off:
                    print("musique_off %s" % reply)
                    tableau = []
                    tableau.append(cle['musique_off']['command'])
                    for i in cle['musique_off']['args']:
                        tableau.append(i)
                    subprocess.Popen( list(tableau) ).pid

                # elif reply in corona:
                    # print("corona")
                    # subprocess.Popen( ['firefox-esr', 'http://gangand.net/cc/coro/stats/index.php?device=PC']).pid

                elif reply in corona:
                    print("corona")
                    subprocess.Popen( ['chromium-browser', 'http://gangand.net/cc/coro/stats/index.php?device=PC']).pid

                    tableau = []
                    choix = cle['corona']
                    if ( choix['action'] == 'browser' ):
                            subprocess.Popen( ['chromium-browser', choix['site'] ] ).pid
                    else:
                            tableau.append(r['command'])
                            for i in r['args']:
                                tableau.append(i)
                            subprocess.Popen( list(tableau) ).pid

                elif reply.split()[0] in musique:
                    print("Vous avez dit: %s" % reply)
                    liste = reply.split(' ')
                    print("Recherche de musique ciblée sur %s" % ' '.join(liste[1:]))
                    # recherche_musique = 'https://www.google.com/search?q=' + ('+').join(liste)
                    # print(recherche_google)
                    # subprocess.Popen( ['chromium-browser', recherche_google]).pid

                else:
                    print("You said: %s" % reply)
                    liste = reply.split(' ')
                    recherche_google = 'https://www.google.com/search?q=' + ('+').join(liste)
                    print(recherche_google)
                    subprocess.Popen( ['chromium-browser', recherche_google]).pid

                # else:
                    # print("You said: %s" % reply)
                    # os.system("flite -o /tmp/flite.wav -t %s " % reply)

            except sr.UnknownValueError:
                print("L'API Google API n'a pas compris ...")
            except sr.RequestError as e:
                print("!")
                #print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e))

    except KeyboardInterrupt:
        pass


def lancement_intelligent():
    """ Utiliser un fichier .ini
    plus facile à éditer """
    try:
        print("Un instant SVP ...")
        with m as source: r.adjust_for_ambient_noise(source)
        # The above line takes an ambient sample of noise to set threshhold levels.
        # This may not work on all microphones and should be tweaked as needed
        while True:
            print("Prêt, veuillez parler. (Presser Ctrl+c ou dire quitter pour quitter)")
            with m as source: audio = r.listen(source)
            print(".")
            try:
                # value = r.recognize_google(audio)
                value = r.recognize_google(audio, language="fr-FR")
                # passer en francais
                # https://stackoverflow.com/questions/49732536/how-to-change-the-language-of-google-speech-recognition

                if str is bytes:
                    reply = "{}".format(value).encode("utf-8")
                else:
                    reply = "{}".format(value)
                print("reply = %s " % reply)

                if reply in exitWord:
                    quit()

                # on est ici


            except sr.UnknownValueError:
                print("L'API Google API n'a pas compris ...")
            except sr.RequestError as e:
                print("!")
                #print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e))

    except KeyboardInterrupt:
        pass



lancement_original()