package com.rssuper.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.rssuper.repository.SubscriptionRepository import com.rssuper.state.State import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class SubscriptionViewModel( private val subscriptionRepository: SubscriptionRepository ) : ViewModel() { private val _subscriptionsState = MutableStateFlow>>(State.Idle) val subscriptionsState: StateFlow>> = _subscriptionsState.asStateFlow() private val _enabledSubscriptionsState = MutableStateFlow>>(State.Idle) val enabledSubscriptionsState: StateFlow>> = _enabledSubscriptionsState.asStateFlow() fun loadAllSubscriptions() { viewModelScope.launch { subscriptionRepository.getAllSubscriptions().collect { state -> _subscriptionsState.value = state } } } fun loadEnabledSubscriptions() { viewModelScope.launch { subscriptionRepository.getEnabledSubscriptions().collect { state -> _enabledSubscriptionsState.value = state } } } fun setEnabled(id: String, enabled: Boolean) { viewModelScope.launch { try { subscriptionRepository.setEnabled(id, enabled) loadEnabledSubscriptions() } catch (e: Exception) { _enabledSubscriptionsState.value = State.Error("Failed to update subscription enabled state", e) } } } fun setError(id: String, error: String?) { viewModelScope.launch { try { subscriptionRepository.setError(id, error) } catch (e: Exception) { _subscriptionsState.value = State.Error("Failed to set subscription error", e) } } } fun updateLastFetchedAt(id: String, lastFetchedAt: Long) { viewModelScope.launch { try { subscriptionRepository.updateLastFetchedAt(id, lastFetchedAt) } catch (e: Exception) { _subscriptionsState.value = State.Error("Failed to update last fetched time", e) } } } fun updateNextFetchAt(id: String, nextFetchAt: Long) { viewModelScope.launch { try { subscriptionRepository.updateNextFetchAt(id, nextFetchAt) } catch (e: Exception) { _subscriptionsState.value = State.Error("Failed to update next fetch time", e) } } } fun refreshSubscriptions() { loadAllSubscriptions() loadEnabledSubscriptions() } }