import urllib3
import requests
import json
import os
import shutil
import subprocess
baseurl="http://127.0.0.1:8774/"
voicelisturl=(baseurl+"/voices")
speakurl=(baseurl+"/forward")
voicejson=requests.get(voicelisturl).content
voiceinfo=json.loads(voicejson)

def menu(options,prompt=None):
    while 1:
        if(prompt is None):
            pass
        else:
            print(prompt)
        for i in options:
            print(str(options.index(i)+1)+":"+i)
        selected=input()
        if(not selected.isnumeric()):
            continue
        else:
            selected=int(selected)
        if(selected<=len(options)):
            return options[int(selected-1)]
            break

class engine:
    def list(self,voiceinfo=voiceinfo):
        return list(voiceinfo.get("data").get("catalog").keys())

    def getvoicesfor(self,engname):
        return list(voiceinfo.get("data").get("catalog").get(engname))

    def memspeak(self,text,voiceid,speed=50,pitch=50,volume=100):
        return(requests.get(urllib3.util.parse_url(str(speakurl+"?text="+text+"&voice="+voiceid+"&speed="+str(speed)+"&pitch="+str(pitch)+"&volume="+str(volume)))).content)
    def speak(self,text,voiceid,speed=50,pitch=50,volume=100):
        wavdata=(requests.get(urllib3.util.parse_url(str(speakurl+"?text="+text+"&voice="+voiceid+"&speed="+str(speed)+"&pitch="+str(pitch)+"&volume="+str(volume)))).content)
        f=open("data.wav","wb")
        f.write(wavdata)
        f.close()
        subprocess.call(executable=shutil.which("play"),args=['play','-t','wav','-q','data.wav'])
        os.remove("data.wav")
    def speaktofile(self,text,voiceid,file,speed=50,pitch=50,volume=100):
        f=open(file,"wb")
        f.write((requests.get(urllib3.util.parse_url(str(speakurl+"?text="+text+"&voice="+voiceid+"&speed="+str(speed)+"&pitch="+str(pitch)+"&volume="+str(volume)))).content))
        f.close()
        return True

e=engine()
englist=e.list()
eng=os.environ.get("MTTS_ENGINE")
voiceid=os.environ.get("MTTS_VOICEID")
speed=os.environ.get("MTTS_SPEED")
pitch=os.environ.get("MTTS_PITCH")
volume=os.environ.get("MTTS_VOLUME")
file=os.environ.get("MTTS_FILE")
if(voiceid is None):
    eng=menu(englist,"Select Engine")
    voices=e.getvoicesfor(eng)
    selvoice=menu([v.get("name") for v in voices if(v.get("name"))],"select voice")
    voiceid=[v.get("id") for v in voices if(v.get("name")==selvoice)][0]
while 1:
    text=input()
    if(speed is None or volume is None or pitch is None):
        if file is None:
            e.speak(text,voiceid)
        else:
            e.speaktofile(text,file=file,speed=speed,pitch=pitch,volume=volume,voiceid=voiceid)
    else:
        if file is None:
            e.speak(text,file=file,speed=speed,pitch=pitch,volume=volume,voiceid=voiceid)
        else:
            e.speaktofile(text,file=file,speed=speed,pitch=pitch,volume=volume,voiceid=voiceid)
