package eu.friedcutlet.yokan.ui.screens.activity 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.observe import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.DbTrackSearch import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId import eu.friedcutlet.yokan.services.tracking.TrackerService import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId import eu.friedcutlet.yokan.services.tracking.orderedTrackers import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext data class TrackerLibraryState( val trackers: List = emptyList(), val selectedTracker: TrackerService? = null, /** The tracker library's own item-type cursor, seeded from the root one. */ val itemType: ItemType = ItemType.Manga, /** Signed-in account of [selectedTracker], if any. */ val account: DbTrackPreference? = null, val sections: List = emptyList(), /** Section label → loaded entries. */ val sectionResults: Map> = emptyMap(), /** Non-blank while a search result section is shown. */ val submittedQuery: String = "", val searchResults: List = emptyList(), val loading: Boolean = false, val error: String? = null, /** Library titles of [itemType] keyed by trimmed, lower-cased name. */ val libraryByTitle: Map = emptyMap(), ) /** * Tracker entries don't carry a library id, so a case-insensitive title match is the closest * approximation of "already in the library". */ internal fun TrackerLibraryState.matchInLibrary(search: DbTrackSearch): Manga? = search.title?.trim()?.lowercase()?.let(libraryByTitle::get) class TrackerLibraryViewModel( allTrackers: List, private val repository: YokanRepository, settings: SettingsStore, initialItemType: ItemType, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val _state = MutableStateFlow( TrackerLibraryState(itemType = initialItemType, sections = trackerLibrarySections(-1, initialItemType)), ) val state: StateFlow = _state.asStateFlow() private var loadJob: Job? = null private var searchJob: Job? = null init { viewModelScope.launch { settings.db.map { orderedTrackers(allTrackers, it) }.distinctUntilChanged().collect { trackers -> val current = state.value // A changed tracker count resets the selection to the first tracker; a reorder keeps it. val keep = current.selectedTracker != null && trackers.size == current.trackers.size val selected = if (keep) current.selectedTracker else trackers.firstOrNull() _state.update { it.copy(trackers = trackers) } selectTracker(selected) } } viewModelScope.launch { combine( _state.map { it.selectedTracker?.syncId }.distinctUntilChanged(), repository.snapshots.map { it.trackPreferences }.distinctUntilChanged(), ) { syncId, preferences -> syncId?.let { id -> preferences.firstOrNull { it.syncId == id.toLong() } } } .collect { account -> _state.update { it.copy(account = account) } } } viewModelScope.launch { combine( _state.map { it.itemType }.distinctUntilChanged(), repository.observe({ it.mangas to it.settings }, workDispatcher) { }, ) { type, _ -> type } .map { type -> repository.allTitles(type).associateBy { it.name.trim().lowercase() } } .flowOn(workDispatcher) .collect { titles -> _state.update { it.copy(libraryByTitle = titles) } } } } fun selectTracker(tracker: TrackerService?) { if (tracker === state.value.selectedTracker) return _state.update { it.copy(selectedTracker = tracker) } clearSearch() load() } fun selectItemType(itemType: ItemType) { if (itemType == state.value.itemType) return _state.update { it.copy(itemType = itemType) } clearSearch() load() } /** Reloads every section of the selected tracker, one after another. */ fun load() { val current = state.value val sections = trackerLibrarySections(current.selectedTracker?.syncId ?: -1, current.itemType) _state.update { it.copy(sections = sections) } val tracker = current.selectedTracker ?: return loadJob?.cancel() _state.update { it.copy(loading = true, error = null, sectionResults = emptyMap()) } loadJob = viewModelScope.launch { sections.forEach { spec -> catchingNonCancellation { withContext(workDispatcher) { if (spec.rankingType == null) { tracker.fetchUserData(spec.isMangaFlag) } else { tracker.fetchGeneralData(spec.isMangaFlag, spec.rankingType) } } }.onSuccess { entries -> _state.update { it.copy(sectionResults = it.sectionResults + (spec.label to entries)) } }.onFailure { failure -> // User lists often require auth; only surface errors from public sections. if (spec.rankingType != null) _state.update { it.copy(error = it.error ?: failure.message) } } } _state.update { it.copy(loading = false) } } } fun search(text: String) { val current = state.value val tracker = current.selectedTracker ?: return if (text.isBlank()) { clearSearch() return } val isManga = current.itemType != ItemType.Anime _state.update { it.copy(submittedQuery = text) } searchJob?.cancel() searchJob = viewModelScope.launch { catchingNonCancellation { withContext(workDispatcher) { tracker.search(text, isManga) } } .onSuccess { results -> _state.update { it.copy(searchResults = results) } } .onFailure { failure -> _state.update { it.copy(error = failure.message ?: "Search failed") } } } } fun clearSearch() { searchJob?.cancel() _state.update { it.copy(submittedQuery = "", searchResults = emptyList()) } } /** Binds [manga] to [search], tagged with the selected tracker. */ fun bindToLibrary(manga: Manga, search: DbTrackSearch) { val syncId = state.value.selectedTracker?.syncId val payload = if (syncId != null) search.copy(syncId = syncId) else search repository.bindTrack(manga.id, payload, manga.itemType) } } /** * One horizontally-scrolling row in the tracker library. `rankingType == null` * loads the user's own list (Continue reading/watching); otherwise the key is * handed to [TrackerService.fetchGeneralData]. * `isMangaFlag` mirrors Mangayomi's parameter reuse — for Simkl/Trakt it means * "movies" instead of "manga". */ data class TrackerLibrarySectionSpec( val label: String, val rankingType: String?, val isMangaFlag: Boolean, ) /** Ranking/browse sections exist for the Mangayomi providers and the metadata source only ([trackerLibrarySections]). */ internal val TrackerService.hasTrackerLibrary: Boolean get() = isMetadataSource || syncId in setOf(MalTrackerSyncId, AnilistTrackerSyncId, KitsuTrackerSyncId, SimklTrackerSyncId, TraktTrackerSyncId) /** Provider-specific section lists mirroring Mangayomi's tracker_library_screen.dart. */ internal fun trackerLibrarySections(syncId: Int, itemType: ItemType): List { val isAnime = itemType == ItemType.Anime return when (syncId) { MalTrackerSyncId -> if (isAnime) { listOf( TrackerLibrarySectionSpec("Continue watching", null, false), TrackerLibrarySectionSpec("Airing Anime", "airing", false), TrackerLibrarySectionSpec("Popular Anime", "bypopularity", false), TrackerLibrarySectionSpec("Upcoming Anime", "upcoming", false), ) } else { listOf( TrackerLibrarySectionSpec("Continue reading", null, true), TrackerLibrarySectionSpec("Popular Manga", "bypopularity", true), TrackerLibrarySectionSpec("Top Manga", "manga", true), TrackerLibrarySectionSpec("Top Manhwa", "manhwa", true), TrackerLibrarySectionSpec("Top Manhua", "manhua", true), ) } AnilistTrackerSyncId -> if (isAnime) { listOf( TrackerLibrarySectionSpec("Continue watching", null, false), TrackerLibrarySectionSpec("Upcoming Anime", "upcoming", false), TrackerLibrarySectionSpec("Popular Anime", "popular", false), TrackerLibrarySectionSpec("Trending Anime", "trending", false), TrackerLibrarySectionSpec("Latest Anime", "latest", false), ) } else { listOf( TrackerLibrarySectionSpec("Continue reading", null, true), TrackerLibrarySectionSpec("Upcoming Manga", "upcoming", true), TrackerLibrarySectionSpec("Popular Manga", "popular", true), TrackerLibrarySectionSpec("Trending Manga", "trending", true), TrackerLibrarySectionSpec("Latest Manga", "latest", true), ) } KitsuTrackerSyncId -> if (isAnime) { listOf( TrackerLibrarySectionSpec("Continue watching", null, false), TrackerLibrarySectionSpec("Popular Anime", "popular", false), TrackerLibrarySectionSpec("Latest Anime", "latest", false), TrackerLibrarySectionSpec("Best Rated Anime", "best", false), ) } else { listOf( TrackerLibrarySectionSpec("Continue reading", null, true), TrackerLibrarySectionSpec("Popular Manga", "popular", true), TrackerLibrarySectionSpec("Latest Manga", "latest", true), TrackerLibrarySectionSpec("Best Rated Manga", "best", true), ) } SimklTrackerSyncId -> listOf( TrackerLibrarySectionSpec("Continue watching movies", null, true), TrackerLibrarySectionSpec("Continue watching series", null, false), TrackerLibrarySectionSpec("Trending Movies", "trending", true), TrackerLibrarySectionSpec("Trending Series", "trending", false), TrackerLibrarySectionSpec("Airing Series", "airing", false), TrackerLibrarySectionSpec("Top Series (All Time)", "best", false), ) TraktTrackerSyncId -> listOf( TrackerLibrarySectionSpec("Continue watching movies", null, true), TrackerLibrarySectionSpec("Continue watching series", null, false), TrackerLibrarySectionSpec("Trending Movies", "trending", true), TrackerLibrarySectionSpec("Trending Series", "trending", false), TrackerLibrarySectionSpec("Popular Movies", "popular", true), TrackerLibrarySectionSpec("Popular Series", "popular", false), TrackerLibrarySectionSpec("Top Movies (All Time)", "favorited/all", true), TrackerLibrarySectionSpec("Top Series (All Time)", "favorited/all", false), ) else -> { val isManga = !isAnime listOf( TrackerLibrarySectionSpec(if (isAnime) "Continue watching" else "Continue reading", null, isManga), TrackerLibrarySectionSpec("Trending", "trending", isManga), TrackerLibrarySectionSpec("Popular", "popular", isManga), TrackerLibrarySectionSpec("Top", "top", isManga), ) } } }