package it.danieleverducci.openweddingapp.entities

import android.graphics.Color
import it.danieleverducci.openweddingapp.Config
import it.danieleverducci.openweddingapp.utils.ViewUtils
import org.json.JSONException
import org.json.JSONObject
import java.text.Normalizer

class User: Jsonable {
    val id: Int
    val name: String
    val surname: String
    val code: String
    val picture: String?
    val admin: Boolean
    val table: String

    @Throws(JSONException::class)
    constructor(jo: JSONObject) {
        this.id = jo.getInt("id")
        this.name = jo.getString("name")
        this.surname = jo.getString("surname")
        this.code = jo.getString("code")
        this.picture = if (jo.isNull("picture") || jo.optString("picture") == "null") null else jo.optString("picture")
        this.admin = jo.optBoolean("admin", false)
        this.table = jo.getString("table")
    }

    override fun toJson(): JSONObject {
        val jo = JSONObject()
        jo.put("id", this.id)
        jo.put("name", this.name)
        jo.put("surname", this.surname)
        jo.put("code", this.code)
        jo.put("picture", this.picture)
        jo.put("admin", this.admin)
        jo.put("table", this.table)
        return jo
    }

    val pictureUrl: String?
        get() {
            if (picture == null)
                return null
            if (picture.startsWith("http")) {
                return picture
            } else {
                return "${Config.MEDIA_BASE_URL}${Config.USER_PICTURE_PATH}${picture}"
            }
        }

    // Badge color calculated on first 3 name and surname letters
    val badgeColor: Int
        get() {
            val r = (ViewUtils.getUserBadgeColorComponentFromString(name, 0) + ViewUtils.getUserBadgeColorComponentFromString(surname, 0)) / 2
            val g = (ViewUtils.getUserBadgeColorComponentFromString(name, 1) + ViewUtils.getUserBadgeColorComponentFromString(surname, 1)) / 2
            val b = (ViewUtils.getUserBadgeColorComponentFromString(name, 2) + ViewUtils.getUserBadgeColorComponentFromString(surname, 2)) / 2
            return Color.rgb(r, g, b)
        }



}