package bou.amine.apps.readerforselfossv2.android.utils

import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import bou.amine.apps.readerforselfossv2.android.R
import bou.amine.apps.readerforselfossv2.android.model.toTextDrawableString
import com.google.android.material.imageview.ShapeableImageView
import kotlin.math.abs

class CircleImageView
    @JvmOverloads
    constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0,
    ) : RelativeLayout(context, attrs, defStyleAttr) {
        val view: View
        val imageView: ShapeableImageView
        val textView: TextView

        private val colorScheme =
            listOf(
                -0x1a8c8d,
                -0xf9d6e,
                -0x459738,
                -0x6a8a33,
                -0x867935,
                -0x9b4a0a,
                -0xb03c09,
                -0xb22f1f,
                -0xb24954,
                -0x7e387c,
                -0x512a7f,
                -0x759b,
                -0x2b1ea9,
                -0x2ab1,
                -0x48b3,
                -0x5e7781,
                -0x6f5b52,
            )

        init {
            view = LayoutInflater.from(context).inflate(R.layout.circle_image_view, this, true)
            imageView = view.findViewById(R.id.circleImage)
            textView = view.findViewById(R.id.circleText)
        }

        fun setBackgroundAndText(text: String) {
            val circleDrawable = GradientDrawable()
            val color = colorFromIdentifier(text)
            circleDrawable.setColor(color)
            imageView.setImageDrawable(circleDrawable)

            textView.text = text.toTextDrawableString()
        }

        private fun colorFromIdentifier(key: String): Int {
            return colorScheme[abs(key.hashCode()) % colorScheme.size]
        }
    }
