package com.example.lexilearn.ui.views.pLearnNumber

import android.app.Application
import android.speech.tts.TextToSpeech
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.lexilearn.utils.generateAlphabetList
import com.example.lexilearn.utils.generateNumberList
import java.util.*

class LearNumberViewModel(application: Application) : AndroidViewModel(application),
    TextToSpeech.OnInitListener {

    private var tts: TextToSpeech? = null
    private val _isTTSInitialized = MutableLiveData(false)
    val isTTSInitialized: LiveData<Boolean> = _isTTSInitialized
    val alphabetList = generateNumberList()

    init {
        // Inisialisasi TextToSpeech saat ViewModel pertama kali diinisialisasi
        tts = TextToSpeech(application, this)
    }

    // Fungsi yang dipanggil ketika TextToSpeech sudah diinisialisasi
    override fun onInit(status: Int) {
        if (status == TextToSpeech.SUCCESS) {
            tts?.language = Locale.ENGLISH
            _isTTSInitialized.value = true
        } else {
            _isTTSInitialized.value = false
        }
    }

    // Fungsi untuk berbicara
    fun speakLetter(letter: String) {
        // Memastikan TextToSpeech sudah diinisialisasi
        if (_isTTSInitialized.value == true) {
            tts?.speak(letter, TextToSpeech.QUEUE_FLUSH, null, null)
        }
    }

    // Jangan lupa untuk melepaskan resource saat ViewModel dihancurkan
    override fun onCleared() {
        tts?.stop()
        tts?.shutdown()
        super.onCleared()
    }
}
