Replace move profile field ajax page with Kotlin version
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / ajax / MoveProfileFieldAjaxPage.kt
diff --git a/src/main/kotlin/net/pterodactylus/sone/web/ajax/MoveProfileFieldAjaxPage.kt b/src/main/kotlin/net/pterodactylus/sone/web/ajax/MoveProfileFieldAjaxPage.kt
new file mode 100644 (file)
index 0000000..e2b039b
--- /dev/null
@@ -0,0 +1,41 @@
+package net.pterodactylus.sone.web.ajax
+
+import net.pterodactylus.sone.data.Profile
+import net.pterodactylus.sone.data.Profile.Field
+import net.pterodactylus.sone.data.Sone
+import net.pterodactylus.sone.utils.parameters
+import net.pterodactylus.sone.web.WebInterface
+import net.pterodactylus.sone.web.page.FreenetRequest
+
+/**
+ * AJAX page that lets the user move a profile field up or down.
+ *
+ * @see net.pterodactylus.sone.data.Profile#moveFieldUp(Field)
+ * @see net.pterodactylus.sone.data.Profile#moveFieldDown(Field)
+ */
+class MoveProfileFieldAjaxPage(webInterface: WebInterface) : LoggedInJsonPage("moveProfileField.ajax", webInterface) {
+
+       override fun createJsonObject(currentSone: Sone, request: FreenetRequest) =
+                       currentSone.profile.let { profile ->
+                               request.parameters["field"]
+                                               ?.let(profile::getFieldById)
+                                               ?.let { processField(currentSone, profile, it, request.parameters["direction"]) }
+                                               ?: createErrorJsonObject("invalid-field-id")
+                       }
+
+       private fun processField(currentSone: Sone, profile: Profile, field: Field, direction: String?) =
+                       try {
+                               when (direction) {
+                                       "up" -> profile.moveFieldUp(field)
+                                       "down" -> profile.moveFieldDown(field)
+                                       else -> null
+                               }?.let {
+                                       currentSone.profile = profile
+                                       webInterface.core.touchConfiguration()
+                                       createSuccessJsonObject()
+                               } ?: createErrorJsonObject("invalid-direction")
+                       } catch (e: IllegalArgumentException) {
+                               createErrorJsonObject("not-possible")
+                       }
+
+}