using System.Speech.Recognition;
using System.Speech.Synthesis;
using ToolsServices;


namespace UI.Services
{
    public partial class SpeechService
    {

        SpeechSynthesizer _synth = new SpeechSynthesizer();

        private int VitesseLecture = 3;
        private int VolumeSon = 50;


        public SpeechService(int vitesseLecture, int volumeSon)
        {
            VitesseLecture = vitesseLecture;
            VolumeSon = volumeSon;

            InitSpeech();
            
            recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("fr-FR"));
            InitRecognizer();
        }

        public void Lire(string txt)
        {
            try
            {
                _synth.SpeakAsyncCancelAll(); // si un texte est déjà en cours
                _synth.SpeakAsync(txt);
            }
            catch(Exception ex)
            {
                LoggerService.LogError($"SpeechService.Lire : {ex.Message}");
            }
        }

        private void InitSpeech()
        {
            _synth.SetOutputToDefaultAudioDevice();
            _synth.Rate = VitesseLecture;     // -10 (lent) à +10 (rapide)
            _synth.Volume = VolumeSon; // 0 à 100
        }

        
        private SpeechRecognitionEngine recognizer;
        private string dictationResult = "";
        public string DictationResult => dictationResult;

        public void Parler()
        {
            dictationResult = "";

            recognizer.SetInputToDefaultAudioDevice();
            recognizer.RecognizeAsync(RecognizeMode.Multiple);
        }

        public void Stop()
        {
            recognizer.RecognizeAsyncStop();
        }

        private void InitRecognizer()
        {
            try
            {
                // Dictée libre (reconnaissance générale)

                recognizer.LoadGrammar(new DictationGrammar()); // dictée libre
                recognizer.SpeechRecognized += Recognizer_SpeechRecognized;
            }
            catch (Exception ex)
            {
                LoggerService.LogError($"Erreur initialisation reco vocale : {ex.Message}");
            }
        }

        private void Recognizer_SpeechRecognized(object? sender, SpeechRecognizedEventArgs e)
        {
            // Utiliser le Dispatcher du thread courant (WPF)
            System.Windows.Application.Current.Dispatcher.Invoke(() =>
            {
                var txt = e.Result.Text + " ";
                dictationResult += txt;
                LoggerService.LogDebug($"Recognizer_SpeechRecognized : {txt}");
            });
        }
        
    }
}
