Use logging method that’s present in Java 1.7
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / core / SoneChangeCollector.kt
1 package net.pterodactylus.sone.core
2
3 import net.pterodactylus.sone.data.Post
4 import net.pterodactylus.sone.data.PostReply
5 import net.pterodactylus.sone.data.Sone
6
7 /**
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.
11  */
12 class SoneChangeCollector(private val oldSone: Sone) {
13
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?>()
18
19         fun onNewPost(postProcessor: (Post) -> Unit) =
20                         newPostEventCreators.add { postProcessor(it).let { null } }.let { this }
21
22         fun newPostEvent(postEventCreator: (Post) -> Any?) =
23                         newPostEventCreators.add(postEventCreator).let { this }
24
25         fun onNewPostReply(postReplyProcessor: (PostReply) -> Unit) =
26                         newPostReplyEventCreators.add { postReplyProcessor(it).let { null } }.let { this }
27
28         fun newPostReplyEvent(postReplyEventCreator: (PostReply) -> Any?) =
29                         newPostReplyEventCreators.add(postReplyEventCreator).let { this }
30
31         fun removedPostEvent(postEventCreator: (Post) -> Any?) =
32                         removedPostEventCreators.add(postEventCreator).let { this }
33
34         fun onRemovedPostReply(postReplyEventCreator: (PostReply) -> Any?) =
35                         removedPostReplyEventCreators.add(postReplyEventCreator).let { this }
36
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)
45                 }
46                 return events
47         }
48
49 }