package eu.friedcutlet.yokan.ui.screens.discovery import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory import eu.friedcutlet.yokan.services.extensions.RemoteManga import eu.friedcutlet.yokan.services.extensions.SourceRelatedGroup import eu.friedcutlet.yokan.services.extensions.withSourceRuntime import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @Immutable internal data class SourceRelatedState( val title: String = "", val loading: Boolean = false, val supported: Boolean? = null, val groups: List = emptyList(), val error: String? = null, val sourceId: Long? = null, val parentUrl: String? = null, val openedTitleId: Long? = null, val opening: Boolean = false, ) internal class SourceRelatedViewModel( private val mangaId: Long, private val repository: YokanRepository, private val database: YokanDatabase, private val runtimes: ExtensionRuntimeFactory, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val _state = MutableStateFlow(SourceRelatedState(loading = true)) val state = _state.asStateFlow() private var loadJob: Job? = null init { refresh() } fun refresh() { if (loadJob?.isActive == true) return loadJob = viewModelScope.launch { _state.update { it.copy(loading = true, error = null) } catchingNonCancellation { val manga = withContext(workDispatcher) { repository.manga(mangaId) } val source = manga?.sourceId?.let { withContext(workDispatcher) { repository.source(it) } } if (manga == null || source == null || manga.isLocalArchive || manga.link.isBlank()) { _state.update { it.copy(title = manga?.name.orEmpty(), supported = false, sourceId = null, groups = emptyList()) } } else { val result = runtimes.withSourceRuntime(database, source.id) { it.related(manga.link) } // The source/title may have been removed or rebound during the request. val current = withContext(workDispatcher) { repository.manga(mangaId) } check(current != null && current.sourceId == source.id && current.link == manga.link && repository.source(source.id) != null) { "The source or title changed. Open related entries again." } _state.update { it.copy(title = current.name, supported = result.supported, groups = result.groups, sourceId = source.id, parentUrl = manga.link) } } }.onFailure { error -> _state.update { it.copy(error = error.message ?: "Unable to load related entries") } } _state.update { it.copy(loading = false) } } } fun open(item: RemoteManga) { val current = _state.value if (current.opening || current.openedTitleId != null || current.groups.none { item in it.items }) return val sourceId = current.sourceId ?: return _state.update { it.copy(opening = true) } // One transaction validates ownership and resolves an existing entry without changing favourites. viewModelScope.launch { catchingNonCancellation { withContext(workDispatcher) { database.batch { val source = repository.source(sourceId) ?: error("The source was removed. Reload related entries.") val parent = repository.manga(mangaId) check(parent != null && parent.sourceId == sourceId && parent.link == current.parentUrl) { "The title changed. Reload related entries." } repository.upsertRemoteTitle(source, item).id } } }.onSuccess { id -> _state.update { it.copy(openedTitleId = id) } } .onFailure { error -> _state.update { it.copy(error = error.message ?: "Unable to open related entry") } } _state.update { it.copy(opening = false) } } } fun opened() { _state.update { it.copy(openedTitleId = null) } } }