Merge branch 'release-0.9.7'
[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.FreenetRequest
9
10 /**
11  * AJAX page that lets the user move a profile field up or down.
12  *
13  * @see net.pterodactylus.sone.data.Profile#moveFieldUp(Field)
14  * @see net.pterodactylus.sone.data.Profile#moveFieldDown(Field)
15  */
16 class MoveProfileFieldAjaxPage(webInterface: WebInterface) : LoggedInJsonPage("moveProfileField.ajax", webInterface) {
17
18         override fun createJsonObject(currentSone: Sone, request: FreenetRequest) =
19                         currentSone.profile.let { profile ->
20                                 request.parameters["field"]
21                                                 ?.let(profile::getFieldById)
22                                                 ?.let { processField(currentSone, profile, it, request.parameters["direction"]) }
23                                                 ?: createErrorJsonObject("invalid-field-id")
24                         }
25
26         private fun processField(currentSone: Sone, profile: Profile, field: Field, direction: String?) =
27                         try {
28                                 when (direction) {
29                                         "up" -> profile.moveFieldUp(field)
30                                         "down" -> profile.moveFieldDown(field)
31                                         else -> null
32                                 }?.let {
33                                         currentSone.profile = profile
34                                         core.touchConfiguration()
35                                         createSuccessJsonObject()
36                                 } ?: createErrorJsonObject("invalid-direction")
37                         } catch (e: IllegalArgumentException) {
38                                 createErrorJsonObject("not-possible")
39                         }
40
41 }