package com.za.common.speech

import android.annotation.SuppressLint
import android.content.Context
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import com.za.common.log.LogUtil
import java.util.Locale

@SuppressLint("StaticFieldLeak")
object TTSManager {
    private var tts: TextToSpeech? = null
    private var context: Context? = null
    private var listener: OnTTSListener? = null


    fun init(context: Context?, onTTSListener: OnTTSListener) {
        this.context = context
        this.listener = onTTSListener
        initTTS()
    }

    private fun initTTS() {
        tts = TextToSpeech(context) { status ->
            if (status == TextToSpeech.SUCCESS) {
                val result = tts?.setLanguage(Locale.getDefault())
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    LogUtil.print("TTS", "Language not supported")
                    listener?.onTTSFailed("Language not supported")
                } else {
                    LogUtil.print("TTS", "TTS initialized successfully")
                    listener?.onTTSInitialized()
                }
            } else {
                LogUtil.print("TTS", "Initialization failed")
                listener?.onTTSFailed("Initialization failed")
            }
        }

        tts?.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
            override fun onStart(utteranceId: String) {
                LogUtil.print("TTS", "Speech started")
            }

            override fun onDone(utteranceId: String) {
                LogUtil.print("TTS", "Speech completed")
                listener?.onTTSSuccess()
            }

            override fun onError(utteranceId: String) {
                LogUtil.print("TTS", "Speech error")
                listener?.onTTSFailed("Speech error")
            }
        })
    }

    fun speak(text: String?) {
        if (tts != null && tts?.isSpeaking == false) {
            tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "uniqueId")
        }
    }

    fun stop() {
        tts?.takeIf { it.isSpeaking }?.stop()
    }

    fun shutdown() {
        tts?.apply {
            stop()
            shutdown()
        }
        tts = null
    }

}

interface OnTTSListener {
    fun onTTSInitialized()
    fun onTTSSuccess()
    fun onTTSFailed(errorMessage: String?)
}