package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.data.toDomainMangas import eu.friedcutlet.yokan.database.DbLocalFolder import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbTitleMetadata import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.util.PlatformLock /** Both local screens share these immutable lists; scan status and folder edits don't rebuild them. */ internal class LocalLibraryProjection(snapshot: YokanDatabaseSnapshot) { // Season records are reached from their parent title's detail screen, never listed separately. private val local = snapshot.mangas.filter { it.isLocalArchive && it.parentId == null }.toDomainMangas(snapshot.settings) private val managed = local.filterNot { it.source.equals("torrent", ignoreCase = true) } val titlesByType = ItemType.entries.associateWith { type -> managed.filter { it.itemType == type } } val browseTitlesByType = ItemType.entries.associateWith { type -> local.filter { it.itemType == type }.sortedBy { it.name.lowercase() } } val reviewQueue = ItemType.entries.flatMap { titlesByType.getValue(it) } .filter { it.metadataServerId == null || it.description.isBlank() }.distinctBy { it.id } private val names = snapshot.mangas.associate { it.id to it.name.orEmpty() } fun titleNames(reconciliation: LocalLibraryReconciliationResult?): Map { reconciliation ?: return emptyMap() val ids = reconciliation.staleTitleCandidates.map { it.id } + reconciliation.duplicateTitleGroups.flatMap { it.ids } return ids.distinct().mapNotNull { id -> names[id]?.let { id to it } }.toMap() } fun overview(folders: List, scan: LocalLibraryScanState) = LocalLibraryOverview( folders = folders, manga = titlesByType.getValue(ItemType.Manga).size, anime = titlesByType.getValue(ItemType.Anime).size, novels = titlesByType.getValue(ItemType.Novel).size, lastScan = scan.lastScan, scanRunning = scan.running, scanError = scan.error, reconciliation = scan.reconciliation, ) } /** Controller-owned and bounded to one revision; collectors can run on different dispatchers. */ internal class LocalLibraryProjectionCache { private val lock = PlatformLock() private var mangas: List? = null private var metadata: List? = null private var cached: LocalLibraryProjection? = null fun get(snapshot: YokanDatabaseSnapshot): LocalLibraryProjection = lock.withLock { if (cached == null || mangas !== snapshot.mangas || metadata != snapshot.settings.titleMetadata) { cached = LocalLibraryProjection(snapshot) mangas = snapshot.mangas metadata = snapshot.settings.titleMetadata } requireNotNull(cached) } }