package eu.friedcutlet.yokan.ui.screens.detail import eu.friedcutlet.yokan.domain.Chapter internal enum class ChapterSelectionOption { All, Invert, Unread, Read, Downloaded, NotDownloaded, Bookmarked, Above, Below, } /** Selected chapter ids; [anchorId] is where range selections start. Chapter lists are in display order. */ internal data class ChapterSelectionState( val ids: Set = emptySet(), val anchorId: Long? = null, ) { fun toggle(id: Long) = copy(ids = if (id in ids) ids - id else ids + id, anchorId = id) fun retainVisible(chapters: List): ChapterSelectionState { val visible = chapters.map { it.id }.toSet() return copy(ids = ids intersect visible, anchorId = anchorId?.takeIf(visible::contains)) } fun rangeTo(chapters: List, id: Long): ChapterSelectionState { val from = chapters.indexOfFirst { it.id == anchorId } val to = chapters.indexOfFirst { it.id == id } return if (to < 0) this else if (from < 0) copy(ids = ids + id, anchorId = id) else copy(ids = ids + chapters.subList(minOf(from, to), maxOf(from, to) + 1).map { it.id }) } /** Adds display rows [first]..[last] (1-based); invalid bounds change nothing. */ fun selectRange(chapters: List, first: Int, last: Int): ChapterSelectionState { if (first !in 1..chapters.size || last !in first..chapters.size) return this val range = chapters.subList(first - 1, last) return copy(ids = ids + range.map(Chapter::id), anchorId = range.first().id) } fun select(chapters: List, option: ChapterSelectionOption): ChapterSelectionState { val anchor = chapters.indexOfFirst { it.id == anchorId } val selected = when (option) { ChapterSelectionOption.All -> chapters.map(Chapter::id).toSet() ChapterSelectionOption.Invert -> chapters.map(Chapter::id).toSet() - ids ChapterSelectionOption.Above -> if (anchor < 0) ids else ids + chapters.take(anchor + 1).map(Chapter::id) ChapterSelectionOption.Below -> if (anchor < 0) ids else ids + chapters.drop(anchor).map(Chapter::id) else -> chapters.filter { when (option) { ChapterSelectionOption.Unread -> !it.isRead ChapterSelectionOption.Read -> it.isRead ChapterSelectionOption.Downloaded -> it.downloadSize != null || it.archivePath.isNotBlank() ChapterSelectionOption.NotDownloaded -> it.downloadSize == null && it.archivePath.isBlank() ChapterSelectionOption.Bookmarked -> it.isBookmarked } }.map(Chapter::id).toSet() } return copy(ids = selected, anchorId = anchorId?.takeIf(selected::contains) ?: chapters.firstOrNull { it.id in selected }?.id) } }