CalendarViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/calendar/CalendarViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.calendar23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.YokanRepository6import eu.friedcutlet.yokan.data.toDb7import eu.friedcutlet.yokan.data.toDomain8import eu.friedcutlet.yokan.data.toDomainMangas9import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot10import eu.friedcutlet.yokan.database.DbActivityCategoryFilter11import eu.friedcutlet.yokan.domain.Category12import eu.friedcutlet.yokan.services.library.ActivityCategoryMatcher13import eu.friedcutlet.yokan.domain.ItemType14import eu.friedcutlet.yokan.domain.Manga15import eu.friedcutlet.yokan.domain.UpdateEntry16import eu.friedcutlet.yokan.services.library.LibraryUpdateController17import kotlinx.coroutines.Dispatchers18import kotlinx.coroutines.flow.MutableStateFlow19import kotlinx.coroutines.flow.SharingStarted20import kotlinx.coroutines.flow.StateFlow21import kotlinx.coroutines.flow.combine22import kotlinx.coroutines.flow.distinctUntilChanged23import kotlinx.coroutines.flow.flowOn24import kotlinx.coroutines.flow.stateIn25import kotlinx.coroutines.flow.update26import kotlinx.coroutines.CoroutineDispatcher27import kotlinx.coroutines.launch28import kotlinx.datetime.DateTimeUnit29import kotlinx.datetime.LocalDate30import kotlinx.datetime.TimeZone31import kotlinx.datetime.plus32import kotlinx.datetime.toLocalDateTime3334internal data class CalendarState(35 val itemType: ItemType,36 val today: LocalDate,37 /** Favorite titles of [itemType] by their expected next-update date. */38 val events: Map<LocalDate, List<Manga>> = emptyMap(),39 val updates: List<UpdateEntry> = emptyList(),40 val refreshing: Boolean = false,41 val categories: List<Category> = emptyList(),42 val categoryFilter: DbActivityCategoryFilter = DbActivityCategoryFilter(),43)4445internal class CalendarViewModel(46 initialType: ItemType,47 private val repository: YokanRepository,48 private val libraryUpdates: LibraryUpdateController,49 private val today: LocalDate = currentDate(),50 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,51) : ViewModel() {52 private val itemType = MutableStateFlow(initialType)53 private val refreshing = MutableStateFlow(false)5455 val state: StateFlow<CalendarState> = combine(56 itemType,57 repository.snapshots.distinctUntilChanged { old, new ->58 old.mangas === new.mangas && old.updates === new.updates && old.categories === new.categories &&59 old.settings.titleMetadata == new.settings.titleMetadata && old.settings.features.activity.upcoming == new.settings.features.activity.upcoming60 },61 refreshing,62 ) { type, snapshot, refreshing -> load(type, refreshing, snapshot) }63 .flowOn(workDispatcher)64 // Seeded synchronously so the first frame never flashes the empty state.65 .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), load(initialType, false, repository.snapshots.value))6667 fun selectType(type: ItemType) {68 itemType.update { type }69 }7071 fun updateCategoryFilter(transform: (DbActivityCategoryFilter) -> DbActivityCategoryFilter) {72 val type = itemType.value.toDb()73 repository.updateDbSettings { db -> db.copy(features = db.features.copy(activity = db.features.activity.let { prefs ->74 prefs.withUpcoming(type, transform(prefs.upcoming(type)))75 })) }76 }7778 /** Runs a library update for the selected type; ignored while one is running. */79 fun refresh() {80 if (refreshing.value) return81 refreshing.update { true }82 viewModelScope.launch {83 try {84 libraryUpdates.run(itemType.value)85 } finally {86 refreshing.update { false }87 }88 }89 }9091 private fun load(type: ItemType, refreshing: Boolean, snapshot: YokanDatabaseSnapshot): CalendarState {92 val categories = snapshot.categories.filter { it.forItemType == type.toDb() }.map { it.toDomain() }.sortedBy { it.position }93 val filter = snapshot.settings.features.activity.upcoming(type.toDb())94 val matcher = ActivityCategoryMatcher(filter, categories.mapTo(mutableSetOf()) { it.id })95 val titles = snapshot.mangas.filter { it.itemType == type.toDb() }.toDomainMangas(snapshot.settings)96 val filtered = titles.filter { matcher.matches(it.categories) }97 val byId = filtered.associateBy { it.id }98 return CalendarState(itemType = type, today = today, events = calendarEvents(filtered, today),99 updates = snapshot.updates.mapNotNull { update ->100 val manga = byId[update.mangaId] ?: return@mapNotNull null101 UpdateEntry(update.id, manga.id, update.chapterId ?: 0L, type, manga.name, update.chapterName.orEmpty(),102 manga.source, update.date.orEmpty(), false, update.updatedAt)103 }, refreshing = refreshing, categories = categories, categoryFilter = filter)104 }105}106107internal fun calendarEvents(titles: List<Manga>, today: LocalDate): Map<LocalDate, List<Manga>> =108 titles.filter { it.favorite }.groupBy { manga ->109 today.plus((manga.smartUpdateDays ?: 0).coerceAtLeast(0), DateTimeUnit.DAY)110 }111112@OptIn(kotlin.time.ExperimentalTime::class)113private fun currentDate(): LocalDate =114 kotlin.time.Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date115