package it.danieleverducci.openweddingapp.entities

import android.net.Uri
import com.android.volley.toolbox.JsonObjectRequest
import it.danieleverducci.openweddingapp.Config
import org.json.JSONException
import org.json.JSONObject

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

    /**
     * Constructs a Location object
     * @param locJo: JSONObject returned by the services
     */
    @Throws(JSONException::class)
    constructor(locJo: JSONObject) {
        val localizedLocations = locJo.getJSONObject("localized")
        for (localeId in localizedLocations.keys()) {
            localized.put(localeId, LocalizedLocation(localizedLocations.getJSONObject(localeId)))
        }
        version = locJo.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 LocalizedLocation: Jsonable {
    val name: String
    val content: String
    val picture: String
    val coordinates: Array<Double>

    /**
     * Constructs a Localized Location object
     * @param locJo: 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")
        this.coordinates = arrayOf(
            jo.getJSONObject("coordinates").getDouble("lat"),
            jo.getJSONObject("coordinates").getDouble("lon")
        )
    }

    override fun toJson(): JSONObject {
        val jo = JSONObject()
        jo.put("name", this.name)
        jo.put("content", this.content)
        jo.put("picture", this.picture)
        val coordJo = JSONObject()
        coordJo.put("lat", this.coordinates[0])
        coordJo.put("lon", this.coordinates[1])
        jo.put("coordinates", coordJo)
        return jo
    }

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

    val geoUri: Uri
        get() {
            val lat = this.coordinates[0]
            val lng = this.coordinates[1]
            return Uri.parse(
                "geo:" + lat + "," + lng +
                    "q=" + lat + "," + lng + "(" + name + ")"
            )
        }

    val gooleMapsUri: Uri
        get() {
            val lat = this.coordinates[0]
            val lng = this.coordinates[1]
            return Uri.parse(
                "https://www.google.com/maps/search/?api=1&query=$lat,$lng"
            )
        }

}