package com.jttools.datacontrol.ui.settings

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.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.time.LocalDate
import javax.inject.Inject

@HiltViewModel
class SettingsViewModel @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 consumedMo = stateHolder.snapshot.map { it.consumedMo }.stateIn(
        viewModelScope, SharingStarted.WhileSubscribed(5_000), 0L
    )

    fun updatePlan(
        planLimitMo: Long,
        planPriceEuro: Double,
        overagePricePerMoEuro: Double,
        cutoffIntervalMinutes: Int,
        autoResetEnabled: Boolean
    ) {
        viewModelScope.launch {
            settingsRepository.updatePlan(
                planLimitMo, planPriceEuro, overagePricePerMoEuro, cutoffIntervalMinutes, autoResetEnabled
            )
        }
    }

    fun setStartDate(date: LocalDate) {
        viewModelScope.launch { settingsRepository.setStartDate(date) }
    }

    fun setConsumedMo(consumedMo: Long) {
        viewModelScope.launch { settingsRepository.setConsumedMo(consumedMo, usageRepository.totalMobileBytes()) }
    }

    fun setPassword(password: String?) {
        viewModelScope.launch { settingsRepository.setPassword(password) }
    }

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