package it.danieleverducci.openweddingapp.entities

import it.danieleverducci.openweddingapp.Config
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.util.*

/*
 JSON Example:
    {
        "imageUrl": "https://picsum.photos/200",
        "likes": 23,
        "description": "Descrizione della foto",
        "author": 0
    }
 */

class GalleryItem: Jsonable {
    val id: Int
    val imageUrl: String
    val imageThumbUrl: String
    val likes: Int
    val firstUserLiked: User?
    val description: String
    val author: User
    val created: Date
    var currentUserLike: Like?

    val url: String
    get() {
        if (imageUrl.startsWith("http")) {
            return imageUrl
        } else {
            return "${Config.MEDIA_BASE_URL}${imageUrl}"
        }
    }

    val thumbUrl: String
    get() {
        if (imageThumbUrl.startsWith("http")) {
            return imageThumbUrl
        } else {
            return "${Config.MEDIA_BASE_URL}${imageThumbUrl}"
        }
    }

    @Throws(JSONException::class)
    constructor(jo: JSONObject) {
        this.id = jo.getInt("id")
        this.imageUrl = jo.getString("imageUrl")
        this.imageThumbUrl = jo.getString("imageThumbUrl")
        this.likes = jo.getInt("likes")
        val fujo = jo.optJSONObject("firstUserLiked")
        if(fujo != null) {
            this.firstUserLiked = User(fujo)
        } else {
            this.firstUserLiked = null
        }
        this.description = if (jo.isNull("description") || jo.optString("description") == "null") "" else jo.optString("description")
        this.author = User(jo.getJSONObject("author"))
        this.created = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(jo.getString("created"))
        this.currentUserLike = if (jo.optJSONObject("currentUserLike") == null) null else Like(jo.optJSONObject("currentUserLike"))
    }

    @Throws(JSONException::class)
    constructor(imageUrl: String, imageThumbUrl: String, author: User) {
        this.id = 0
        this.imageUrl = imageUrl
        this.imageThumbUrl = imageThumbUrl
        this.author = author
        this.likes = 0
        this.firstUserLiked = null
        this.description = ""
        this.created = Date()
        this.currentUserLike = null
    }

    override fun toJson(): JSONObject {
        val jo = JSONObject()
        jo.put("id", id)
        jo.put("imageUrl", imageUrl)
        jo.put("imageThumbUrl", imageThumbUrl)
        jo.put("author", author.toJson())
        jo.put("likes", likes)
        jo.put("firstUserLiked", firstUserLiked?.toJson())
        jo.put("description", description)
        jo.put("created", SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(created))
        jo.put("currentUserLiked", currentUserLike)
        return jo
    }

}