package eu.friedcutlet.yokan.ui.screens.extensions import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.toDomain import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory import eu.friedcutlet.yokan.services.extensions.SourceInstallService import eu.friedcutlet.yokan.services.extensions.SourcePreferenceValue import eu.friedcutlet.yokan.services.extensions.mihon.MihonExtensionRuntimeService import eu.friedcutlet.yokan.services.extensions.withSourceRuntime import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** The source row, re-read only when the sources table changes. */ internal fun YokanRepository.observeDbSource(sourceId: Long): Flow = snapshots .distinctUntilChangedBy { it.sources } .map { snapshot -> snapshot.sources.firstOrNull { it.id == sourceId } } .distinctUntilChanged() internal fun YokanRepository.currentDbSource(sourceId: Long): DbSource? = snapshots.value.sources.firstOrNull { it.id == sourceId } internal data class ExtensionDetailUiState( val dbSource: DbSource?, val actionMessage: String? = null, val preferences: List = emptyList(), val preferencesLoading: Boolean = false, /** Stored preference values for this source, by key. */ val storedPreferences: Map = emptyMap(), ) { val source: Source? = dbSource?.toDomain() } /** Extension detail: metadata, uninstall, cookies and the runtime's preference list. */ internal class ExtensionDetailViewModel( private val sourceId: Long, repository: YokanRepository, private val settings: SettingsStore, private val sourceInstall: SourceInstallService, private val runtimeFactory: ExtensionRuntimeFactory, private val database: YokanDatabase, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val _state = MutableStateFlow(ExtensionDetailUiState(repository.currentDbSource(sourceId))) val state: StateFlow = _state.asStateFlow() private val preferenceReloads = MutableStateFlow(0) init { viewModelScope.launch { repository.observeDbSource(sourceId).collect { db -> _state.update { it.copy(dbSource = db) } } } val storedPreferences = settings.db.map { it.sourcePreferences.orEmpty() }.distinctUntilChanged() viewModelScope.launch { storedPreferences.collect { stored -> _state.update { state -> state.copy(storedPreferences = stored.filter { it.sourceId == sourceId }.associate { it.key to it.value }) } } } viewModelScope.launch { // The runtime reads stored values, so every preference write reloads the list. combine(storedPreferences, preferenceReloads) { _, reload -> reload } .collectLatest { reload -> loadPreferences(refresh = reload > 0) } } } private suspend fun loadPreferences(refresh: Boolean) { _state.update { it.copy(preferencesLoading = true) } val preferences = catchingNonCancellation { withContext(workDispatcher) { runtimeFactory.withSourceRuntime(database, sourceId) { service -> if (refresh && service is MihonExtensionRuntimeService) { service.refreshSourcePreferences() } else { service.sourcePreferences() } } } }.getOrDefault(emptyList()) _state.update { it.copy(preferences = preferences, preferencesLoading = false) } } /** Mihon only: asks the extension to rebuild its preference screen. */ fun refreshPreferences() = preferenceReloads.update { it + 1 } fun setPreference(key: String, value: String) = settings.updateDb { it.withSourcePreference(sourceId, key, value) } fun uninstall() { val source = _state.value.source ?: return val deleted = sourceInstall.uninstall(sourceId) _state.update { it.copy(actionMessage = if (deleted) "${source.name} was removed (obsolete)." else "${source.name} uninstalled.") } } fun deleteCookies() { val source = _state.value.source ?: return sourceInstall.deleteCookies(source) _state.update { it.copy(actionMessage = "Cookies deleted for ${source.baseUrl}.") } } }