package bou.amine.apps.readerforselfossv2.android.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import bou.amine.apps.readerforselfossv2.repository.Repository
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch

class AppViewModel(private val repository: Repository) : ViewModel() {
    private val _networkAvailableProvider = MutableSharedFlow<Boolean>()
    val networkAvailableProvider = _networkAvailableProvider.asSharedFlow()
    private var wasConnected = true

    init {
        viewModelScope.launch {
            repository.isConnectionAvailable.collect { isConnected ->
                if (repository.connectionMonitored) {
                    if (isConnected && !wasConnected && repository.connectionMonitored) {
                        _networkAvailableProvider.emit(true)
                        wasConnected = true
                    } else if (!isConnected && wasConnected && repository.connectionMonitored){
                        _networkAvailableProvider.emit(false)
                        wasConnected = false
                    }
                }
            }
        }
    }
}