package com.example.lexilearn.ui.views.pDetailMaterial

import android.app.Application
import android.speech.tts.TextToSpeech
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.repository.MaterialRepository
import com.example.lexilearn.utils.generateNumberList
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.util.*

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

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

    private val repository = MaterialRepository(application)

    private val _materialList = MutableStateFlow<List<MaterialDataModel>>(emptyList())
    val materialList: StateFlow<List<MaterialDataModel>> = _materialList

    fun fetchMaterial(materialListData: List<MaterialDataModel>) {
        _materialList.value = materialListData
    }

    init {
        tts = TextToSpeech(application, this)
    }

    override fun onInit(status: Int) {
        if (status == TextToSpeech.SUCCESS) {
            tts?.language = Locale.ENGLISH
            _isTTSInitialized.value = true
        } else {
            _isTTSInitialized.value = false
        }
    }

    fun speakLetter(letter: String) {
        if (_isTTSInitialized.value == true) {
            tts?.speak(letter, TextToSpeech.QUEUE_FLUSH, null, null)
        }
    }

    override fun onCleared() {
        tts?.stop()
        tts?.shutdown()
        super.onCleared()
    }
}
