package eu.friedcutlet.yokan.ui.screens.library import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.emptySnapshot import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.services.download.ChapterDownloads import eu.friedcutlet.yokan.services.download.DownloadProgress import eu.friedcutlet.yokan.services.download.DownloadRequest import eu.friedcutlet.yokan.services.download.DownloadService import eu.friedcutlet.yokan.services.files.NoFiles import eu.friedcutlet.yokan.services.library.DefaultLocalEntryManagementService import eu.friedcutlet.yokan.services.library.LibraryUpdateController import eu.friedcutlet.yokan.services.library.LibraryUpdateProgress import eu.friedcutlet.yokan.services.library.LibraryUpdateResult import eu.friedcutlet.yokan.services.library.LibraryUpdaterService import eu.friedcutlet.yokan.services.library.LocalLibraryController import eu.friedcutlet.yokan.services.library.LocalLibraryReconciliationResult import eu.friedcutlet.yokan.services.library.LocalLibraryScanResult import eu.friedcutlet.yokan.services.library.LocalLibraryService import eu.friedcutlet.yokan.services.metadata.MetadataLibraryEntry import eu.friedcutlet.yokan.services.metadata.MetadataMedia import eu.friedcutlet.yokan.services.metadata.MetadataService import eu.friedcutlet.yokan.services.notifications.NoNotifications import eu.friedcutlet.yokan.ui.ViewModelTestHost import eu.friedcutlet.yokan.ui.navigation.LibraryRequest import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest @OptIn(ExperimentalCoroutinesApi::class) class LibraryViewModelTest { private val host = ViewModelTestHost() private val dispatcher = host.dispatcher private val database = InMemoryYokanDatabase( emptySnapshot().copy( mangas = listOf( DbManga(id = 1, name = "Alpha", favorite = true), DbManga(id = 2, name = "Beta", favorite = true), DbManga(id = 3, name = "Anime", itemType = DbItemType.Anime, favorite = true), DbManga(id = 4, name = "Browsed"), ), chapters = listOf(DbChapter(id = 11, mangaId = 1, name = "One"), DbChapter(id = 12, mangaId = 1, name = "Two")), ), ) private val repository = DefaultYokanRepository(database) @AfterTest fun tearDown() = host.close() private fun TestScope.viewModel(settings: SettingsStore = SettingsStore(repository, backgroundScope) {}): LibraryViewModel { val localLibrary = LocalLibraryController( localLibrary = NoScanLibrary, entryManagement = DefaultLocalEntryManagementService(database, NoScanLibrary), repository = repository, metadata = NoMetadata, trackers = emptyList(), files = NoFiles, settings = settings, importScope = backgroundScope, ) return host.create { LibraryViewModel( itemType = ItemType.Manga, repository = repository, settings = settings, libraryIndex = LibraryIndexStore(repository, backgroundScope, dispatcher), libraryUpdates = LibraryUpdateController(NoUpdater, repository, NoNotifications, backgroundScope), localLibrary = localLibrary, chapterDownloads = ChapterDownloads(repository, database, NoDownloads, NoNotifications, settings, NoFiles, backgroundScope), libraryRequests = MutableStateFlow(null), workDispatcher = dispatcher, ) } } @Test fun listsOnlyFavouritesOfItsItemType() = runTest(dispatcher) { val vm = viewModel() runCurrent() assertEquals(setOf(1L, 2L), vm.state.value.currentItems.map { it.id }.toSet()) } @Test fun markingTheSelectionReadClearsItAndWritesEveryChapter() = runTest(dispatcher) { val vm = viewModel() runCurrent() vm.onEvent(LibraryEvent.BeginSelection(1)) assertTrue(vm.state.value.selectionMode) vm.onEvent(LibraryEvent.MarkSelectedRead(isRead = true)) runCurrent() assertEquals(emptySet(), vm.state.value.selectedIds) assertTrue(repository.chapters(1).all { it.isRead }) } @Test fun searchShowsImmediatelyAndPersistsAfterTheDebounce() = runTest(dispatcher) { val settings = SettingsStore(repository, backgroundScope) {} val vm = viewModel(settings) runCurrent() vm.onEvent(LibraryEvent.Search("alp")) assertEquals("alp", vm.state.value.query.search) assertEquals("", settings.db.value.libraryQuery(ItemType.Manga).search) advanceTimeBy(251) assertEquals("alp", settings.db.value.libraryQuery(ItemType.Manga).search) } } private object NoScanLibrary : LocalLibraryService { override suspend fun scan() = LocalLibraryScanResult(0, 0, 0) override suspend fun reconcile() = LocalLibraryReconciliationResult() override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null } private object NoMetadata : MetadataService { override suspend fun health(baseUrl: String) = false override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int) = emptyList() override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List> = emptyList() override suspend fun upsertLibraryEntry( baseUrl: String, token: String, mediaId: String, status: String, progress: Int, score: Int?, isFavorite: Boolean, ) = false } private object NoUpdater : LibraryUpdaterService { override suspend fun updateLibrary( itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit, shouldCancel: () -> Boolean, titleIds: Set?, mayStartTitle: suspend () -> Boolean, ) = LibraryUpdateResult(0, 0, 0) override suspend fun updateTitle(mangaId: Long) = false } private object NoDownloads : DownloadService { override suspend fun initialize(poolSize: Int) = Unit override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit override fun cancel(taskId: String) = Unit override fun pause(taskId: String) = Unit override fun resume(taskId: String) = Unit override fun retry(taskId: String) = false override fun storageLocation(taskId: String): String? = null override fun deleteArtifacts(taskId: String) = Unit override fun activeDownloads(): List = emptyList() }