1 package net.pterodactylus.sone.core
3 import net.pterodactylus.sone.data.Post
4 import net.pterodactylus.sone.data.PostReply
5 import net.pterodactylus.sone.data.Sone
8 * Wrapper around a [SoneChangeDetector] that can turn changed elements into
9 * different elements which are then being returned. This can be used to turn
10 * changed elements into events for further processing.
12 class SoneChangeCollector(private val oldSone: Sone) {
14 private val newPostEventCreators = mutableListOf<(Post) -> Any?>()
15 private val removedPostEventCreators = mutableListOf<(Post) -> Any?>()
16 private val newPostReplyEventCreators = mutableListOf<(PostReply) -> Any?>()
17 private val removedPostReplyEventCreators = mutableListOf<(PostReply) -> Any?>()
19 fun onNewPost(postProcessor: (Post) -> Unit) =
20 newPostEventCreators.add { postProcessor(it).let { null } }.let { this }
22 fun newPostEvent(postEventCreator: (Post) -> Any?) =
23 newPostEventCreators.add(postEventCreator).let { this }
25 fun onNewPostReply(postReplyProcessor: (PostReply) -> Unit) =
26 newPostReplyEventCreators.add { postReplyProcessor(it).let { null } }.let { this }
28 fun newPostReplyEvent(postReplyEventCreator: (PostReply) -> Any?) =
29 newPostReplyEventCreators.add(postReplyEventCreator).let { this }
31 fun removedPostEvent(postEventCreator: (Post) -> Any?) =
32 removedPostEventCreators.add(postEventCreator).let { this }
34 fun onRemovedPostReply(postReplyEventCreator: (PostReply) -> Any?) =
35 removedPostReplyEventCreators.add(postReplyEventCreator).let { this }
37 fun detectChanges(newSone: Sone): List<Any> {
38 val events = mutableListOf<Any>()
39 SoneChangeDetector(oldSone).apply {
40 onNewPosts { post -> newPostEventCreators.mapNotNull { it(post) }.forEach { events.add(it) } }
41 onRemovedPosts { post -> removedPostEventCreators.mapNotNull { it(post) }.forEach { events.add(it) } }
42 onNewPostReplies { reply -> newPostReplyEventCreators.mapNotNull { it(reply) }.forEach { events.add(it) } }
43 onRemovedPostReplies { reply -> removedPostReplyEventCreators.mapNotNull { it(reply) }.forEach { events.add(it) } }
44 detectChanges(newSone)