package it.danieleverducci.openweddingapp.entities

import it.danieleverducci.openweddingapp.Config
import org.json.JSONException
import org.json.JSONObject

class GenericDynamicContent: Jsonable {
    val localized = HashMap<String, LocalizedGenericDynamicContent>()
    val version: Int

    /**
     * Constructs a GenericDynamicContent object
     * @param wgJo: JSONObject returned by the services
     */
    @Throws(JSONException::class)
    constructor(wgJo: JSONObject) {
        val localizedGenericDynamicContents = wgJo.getJSONObject("localized")
        for (localeId in localizedGenericDynamicContents.keys()) {
            localized.put(localeId, LocalizedGenericDynamicContent(localizedGenericDynamicContents.getJSONObject(localeId)))
        }
        version = wgJo.getInt("version")
    }

    override fun toJson(): JSONObject {
        val localizedJo = JSONObject()
        for ((localeId, location) in localized) {
            localizedJo.put(localeId, location.toJson())
        }
        val jo = JSONObject()
        jo.put("localized", localizedJo)
        jo.put("version", version)
        return jo
    }
}

class LocalizedGenericDynamicContent: Jsonable {
    val name: String
    val content: String
    val picture: String

    /**
     * Constructs a Localized object
     * @param wgJo: JSONObject returned by the services
     * @param locale: two-letter international code (i.e. "it" or "es")
     */
    @Throws(JSONException::class)
    constructor(jo: JSONObject) {
        this.name = jo.getString("name")
        this.content = jo.getString("content")
        this.picture = jo.getString("picture")
    }

    override fun toJson(): JSONObject {
        val jo = JSONObject()
        jo.put("name", this.name)
        jo.put("content", this.content)
        jo.put("picture", this.picture)
        return jo
    }

    val pictureUrl: String?
        get() {
            if (picture.startsWith("http")) {
                return picture
            } else {
                return "${Config.MEDIA_BASE_URL}/static/media/${picture}"
            }
        }

}