package com.jttools.datacontrol.ui.whitelist

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jttools.datacontrol.data.AppInfo
import com.jttools.datacontrol.data.AppSettings
import com.jttools.datacontrol.data.InstalledAppsRepository
import com.jttools.datacontrol.data.SettingsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class WhitelistViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository,
    private val installedAppsRepository: InstalledAppsRepository
) : ViewModel() {

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

    private val _apps = MutableStateFlow<List<AppInfo>>(emptyList())
    val apps = _apps.asStateFlow()

    private val _loading = MutableStateFlow(true)
    val loading = _loading.asStateFlow()

    init {
        viewModelScope.launch {
            _apps.value = installedAppsRepository.listInstalledApps()
            _loading.value = false
        }
    }

    fun setWhitelisted(packageName: String, whitelisted: Boolean, forWifi: Boolean) {
        viewModelScope.launch {
            val current = if (forWifi) settings.value.whitelistedPackagesWifi else settings.value.whitelistedPackages
            val updated = if (whitelisted) current + packageName else current - packageName
            if (forWifi) settingsRepository.setWhitelistedPackagesWifi(updated) else settingsRepository.setWhitelistedPackages(updated)
        }
    }

    /** Sélectionne ou désélectionne en bloc les paquets [packageNames] (ex : la liste actuellement filtrée à l'écran). */
    fun setWhitelistedBulk(packageNames: List<String>, whitelisted: Boolean, forWifi: Boolean) {
        viewModelScope.launch {
            val current = if (forWifi) settings.value.whitelistedPackagesWifi else settings.value.whitelistedPackages
            val updated = if (whitelisted) current + packageNames else current - packageNames.toSet()
            if (forWifi) settingsRepository.setWhitelistedPackagesWifi(updated) else settingsRepository.setWhitelistedPackages(updated)
        }
    }

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

    fun setShowSystemApps(show: Boolean) {
        viewModelScope.launch { settingsRepository.setShowSystemApps(show) }
    }

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