package it.danieleverducci.openweddingapp.entities

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

class RemoteSettings: Jsonable {
    val version: Int
    val appVersion: Int
    val photoSharingEnabled: Boolean
    val showTableEnabled: Boolean
    val rotateToExifData: Boolean
    val wifiNetworks: ArrayList<WifiNetwork>

    @Throws(JSONException::class)
    constructor(jo: JSONObject) {
        version = jo.getInt("version")
        // appVersion was introduced in version config file version 4
        appVersion = jo.optInt("appVersion",9)  // 9 is last version previous to update check introduction
        photoSharingEnabled = jo.getBoolean("photoSharingEnabled")
        showTableEnabled = jo.getBoolean("showTableEnabled")
        rotateToExifData = jo.optBoolean("rotateToExifData", true)
        wifiNetworks = ArrayList()
        if (jo.has("wifiNetworks")) {
            val wnja = jo.getJSONArray("wifiNetworks")
            for (i in 0 until wnja.length()) {
                val wnjo = wnja.getJSONObject(i)
                wifiNetworks.add(WifiNetwork(wnjo))
            }
        }
    }

    override fun toJson(): JSONObject {
        val jo = JSONObject()
        jo.put("version", version)
        jo.put("appVersion", appVersion)
        jo.put("photoSharingEnabled", photoSharingEnabled)
        jo.put("showTableEnabled", showTableEnabled)
        jo.put("rotateToExifData", rotateToExifData)
        val wnja = JSONArray()
        for (wn in wifiNetworks)
            wnja.put(wn.toJson())
        jo.put("wifiNetworks", wnja)
        return jo
    }
}
