package com.jttools.datacontrol.ui.dashboard

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jttools.datacontrol.data.AppSettings
import com.jttools.datacontrol.data.SettingsRepository
import com.jttools.datacontrol.data.UsageRepository
import com.jttools.datacontrol.service.MonitorStateHolder
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class DashboardViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository,
    private val usageRepository: UsageRepository,
    stateHolder: MonitorStateHolder
) : ViewModel() {

    val settings = settingsRepository.settingsFlow.stateIn(
        viewModelScope, SharingStarted.WhileSubscribed(5_000), AppSettings()
    )

    val snapshot = stateHolder.snapshot

    fun setControlEnabled(enabled: Boolean) {
        viewModelScope.launch { settingsRepository.setControlEnabled(enabled) }
    }

    fun resetPlanNow() {
        viewModelScope.launch { settingsRepository.resetPlan(usageRepository.totalMobileBytes()) }
    }

    suspend fun verifyPassword(password: String): Boolean = settingsRepository.verifyPassword(password)
}
