package com.demoscene.tv.ui

import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.view.View
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.demoscene.tv.R

object MarbleButtonHelper {
    
    private val marbleDrawables = listOf(
        R.drawable.marble_1,
        R.drawable.marble_2,
        R.drawable.marble_3,
        R.drawable.marble_4,
        R.drawable.marble_5,
        R.drawable.marble_6,
        R.drawable.marble_7,
        R.drawable.marble_8,
        R.drawable.marble_9,
        R.drawable.marble_10
    )
    
    fun applyRandomMarble(context: Context, view: View) {
        val randomMarble = marbleDrawables.random()
        val marbleDrawable = ContextCompat.getDrawable(context, randomMarble)
        
        val layers = arrayOf(
            marbleDrawable,
            createBorderDrawable(false)
        )
        val layerDrawable = LayerDrawable(layers)
        
        view.background = layerDrawable
        
        view.setOnFocusChangeListener { v, hasFocus ->
            val newLayers = arrayOf(
                ContextCompat.getDrawable(context, randomMarble),
                createBorderDrawable(hasFocus)
            )
            v.background = LayerDrawable(newLayers)
        }
    }
    
    private fun createBorderDrawable(focused: Boolean): GradientDrawable {
        val drawable = GradientDrawable()
        drawable.shape = GradientDrawable.RECTANGLE
        drawable.cornerRadius = 24f
        if (focused) {
            drawable.setStroke(8, 0xFFFFFFFF.toInt())
        } else {
            drawable.setStroke(2, 0x33FFFFFF.toInt())
        }
        return drawable
    }
    
    fun applyToAllButtons(context: Context, vararg views: View) {
        for (view in views) {
            applyRandomMarble(context, view)
        }
    }
}
