"""One speech worker, with NVDA then JAWS COM and Windows SAPI fallback.

Importing this module does not start a thread or contact a screen reader.
"""
from pathlib import Path
import ctypes, threading, queue, logging
class Speech:
    def __init__(self):
        self._queue=queue.Queue()
        self._thread=None
        self._lock=threading.Lock()
    def submit(self,text):
        with self._lock:
            if self._thread is None:
                self._thread=threading.Thread(target=self._run,name='NTLyntinSpeech',daemon=True)
                self._thread.start()
        self._queue.put(text)
    def _run(self):
        import pythoncom, win32com.client
        pythoncom.CoInitialize()
        nvda=jaws=sapi=None
        try:
            try:
                nvda=ctypes.WinDLL(str(Path(__file__).resolve().parents[1]/'dlls/nvdaControllerClient.dll'))
                nvda.nvdaController_testIfRunning.argtypes=[]
                nvda.nvdaController_testIfRunning.restype=ctypes.c_int
                nvda.nvdaController_speakText.argtypes=[ctypes.c_wchar_p]
                nvda.nvdaController_speakText.restype=ctypes.c_int
                nvda.nvdaController_cancelSpeech.argtypes=[]
                nvda.nvdaController_cancelSpeech.restype=ctypes.c_int
            except OSError: logging.exception('NVDA controller unavailable')
            while True:
                text=self._queue.get()
                try:
                    if nvda and nvda.nvdaController_testIfRunning()==0:
                        if text is None: nvda.nvdaController_cancelSpeech()
                        else: nvda.nvdaController_speakText(text)
                        continue
                    if jaws is None:
                        try: jaws=win32com.client.GetActiveObject('FreedomSci.JawsApi')
                        except Exception: pass
                    if jaws:
                        try:
                            if text is None: jaws.RunScript('StopSpeech')
                            else: jaws.SayString(text,False)
                            continue
                        except Exception: jaws=None
                    if sapi is None: sapi=win32com.client.Dispatch('SAPI.SpVoice')
                    if text is None: sapi.Speak('',3)
                    else: sapi.Speak(text,1)
                except Exception: logging.exception('Speech failed')
                finally: self._queue.task_done()
        finally: pythoncom.CoUninitialize()
speech=Speech()
