package com.devulex.eventorage.rpc

import com.devulex.eventorage.model.SettingsGetResponse
import org.w3c.dom.url.URLSearchParams

suspend fun getSettings(): SettingsGetResponse =
        getAndParseResult("/settings.get", null, ::parseGetSettings)

private fun parseGetSettings(json: dynamic): SettingsGetResponse {
    if (json.error != null) {
        throw GetSettingsException(json.error.toString())
    }
    return SettingsGetResponse(clusterName = json.clusterName, clusterNodes = json.clusterNodes,
            language = json.language, dateFormat = json.dateFormat)
}

class GetSettingsException(message: String) : Throwable(message)

suspend fun updateSetting(name: String, value: String) =
        postAndParseResult("/settings.update", URLSearchParams().apply {
            append("name", name)
            append("value", value)
        }, ::parseUpdateSettingsResponse)

class SettingUpdateException(message: String) : Throwable(message)

private fun parseUpdateSettingsResponse(json: dynamic) {
    if (json.ok == false) {
        throw SettingUpdateException(json.error.toString())
    }
}
