package de.kif.common.model

import kotlinx.serialization.Serializable

@Serializable
data class Color(
    val red: Int,
    val green: Int,
    val blue: Int,
    val alpha: Double = 1.0
) {
    override fun toString(): String {
        return if (alpha >= 1.0) {
            val r = red.toString(16).padStart(2, '0')
            val g = green.toString(16).padStart(2, '0')
            val b = blue.toString(16).padStart(2, '0')
            "#$r$g$b"
        } else {
            "rgba($red, $green, $blue, $alpha)"
        }
    }

    fun calcRedDouble() = red / 255.0

    fun calcGreenDouble() = green / 255.0

    fun calcBlueDouble() = blue / 255.0

    fun calcLuminance(): Double = 0.2126 * calcRedDouble() + 0.7152 * calcGreenDouble() + 0.0722 * calcBlueDouble()

    fun calcTextColor(): Color = if (calcLuminance() < 0.7) WHITE else BLACK

    companion object {
        fun parse(color: String): Color {
            val r: Int
            val g: Int
            val b: Int
            val a: Double
            if (color.startsWith("#")) {
                if (color.length == 3) {
                    r = color.substring(1, 2).toInt(16)
                    g = color.substring(2, 3).toInt(16)
                    b = color.substring(3, 4).toInt(16)
                } else {
                    r = color.substring(1, 3).toInt(16)
                    g = color.substring(3, 5).toInt(16)
                    b = color.substring(5, 7).toInt(16)
                }
                a = 1.0
            } else {
                val split = color.substringAfter("(").substringBefore(")").split(",")
                r = split[0].toInt()
                g = split[1].toInt()
                b = split[2].toInt()
                a = split.getOrNull(3)?.toDouble() ?: 1.0
            }
            return Color(r, g, b, a)
        }

        val WHITE = Color(255, 255, 255)
        val BLACK = Color(51, 51, 51)

        val default = listOf(
            "red" to parse("#F44336"),
            "pink" to parse("#E91E63"),
            "purple" to parse("#9C27B0"),
            "deep-purple" to parse("#673AB7"),
            "indigo" to parse("#3F51B5"),
            "blue" to parse("#1E88E5"),
            "light blue" to parse("#03A9F4"),
            "cyan" to parse("#00BCD4"),
            "teal" to parse("#009688"),
            "green" to parse("#43A047"),
            "light-green" to parse("#7CB342"),
            "lime" to parse("#C0CA33"),
            "yellow" to parse("#FDD835"),
            "amber" to parse("#FFB300"),
            "orange" to parse("#FB8C00"),
            "deep-orange" to parse("#F4511E"),
            "brown" to parse("#795548"),
            "gray" to parse("#9E9E9E"),
            "blue gray" to parse("#607D8B")
        )
    }
}

fun String.parseColor() = Color.parse(this)
