🚧 Add handler for startup event
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / ajax / MoveProfileFieldAjaxPage.kt
1 package net.pterodactylus.sone.web.ajax
2
3 import net.pterodactylus.sone.data.Profile
4 import net.pterodactylus.sone.data.Profile.Field
5 import net.pterodactylus.sone.data.Sone
6 import net.pterodactylus.sone.utils.parameters
7 import net.pterodactylus.sone.web.WebInterface
8 import net.pterodactylus.sone.web.page.*
9 import javax.inject.Inject
10
11 /**
12  * AJAX page that lets the user move a profile field up or down.
13  *
14  * @see net.pterodactylus.sone.data.Profile#moveFieldUp(Field)
15  * @see net.pterodactylus.sone.data.Profile#moveFieldDown(Field)
16  */
17 @ToadletPath("moveProfileField.ajax")
18 class MoveProfileFieldAjaxPage @Inject constructor(webInterface: WebInterface) : LoggedInJsonPage(webInterface) {
19
20         override fun createJsonObject(currentSone: Sone, request: FreenetRequest) =
21                         currentSone.profile.let { profile ->
22                                 request.parameters["field"]
23                                                 ?.let(profile::getFieldById)
24                                                 ?.let { processField(currentSone, profile, it, request.parameters["direction"]) }
25                                                 ?: createErrorJsonObject("invalid-field-id")
26                         }
27
28         private fun processField(currentSone: Sone, profile: Profile, field: Field, direction: String?) =
29                         try {
30                                 when (direction) {
31                                         "up" -> profile.moveFieldUp(field)
32                                         "down" -> profile.moveFieldDown(field)
33                                         else -> null
34                                 }?.let {
35                                         currentSone.profile = profile
36                                         core.touchConfiguration()
37                                         createSuccessJsonObject()
38                                 } ?: createErrorJsonObject("invalid-direction")
39                         } catch (e: IllegalArgumentException) {
40                                 createErrorJsonObject("not-possible")
41                         }
42
43 }