package com.gh.gamecenter.common.view

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.updateLayoutParams
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.databinding.LayoutBasicIconBinding
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor

class BasicIconView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) {

    private var binding: LayoutBasicIconBinding =
        LayoutBasicIconBinding.inflate(LayoutInflater.from(context), this, true)

    private var backGroundColor = R.color.primary_theme_10.toColor(context)
    private var iconColor = Color.parseColor("#000000")
    private var iconResourceId = 0
    private var iconWidth = 0

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }

    init {
        initAttrs(context, attrs)
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.BasicIconView)
        backGroundColor = typedArray.getColor(R.styleable.BasicIconView_background_color, backGroundColor)
        iconColor = typedArray.getColor(R.styleable.BasicIconView_icon_color, iconColor)
        iconResourceId = typedArray.getResourceId(R.styleable.BasicIconView_icon_resource, iconResourceId)
        iconWidth = typedArray.getDimensionPixelSize(R.styleable.BasicIconView_icon_width, 24F.dip2px())
        typedArray.recycle()

        binding.ivIcon.updateLayoutParams<LayoutParams> {
            width = iconWidth
            height = iconWidth
        }
        if (iconResourceId != 0) {
            val drawable = AppCompatResources.getDrawable(context, iconResourceId)
            drawable?.setTint(iconColor)
            binding.ivIcon.setImageDrawable(drawable)
            binding.ivIcon.setColorFilter(iconColor)
        }

        paint.color = backGroundColor
    }

    override fun dispatchDraw(canvas: Canvas) {
        val centerX = width / 2f
        val centerY = height / 2f
        val radius = width.coerceAtMost(height) / 2f
        canvas.drawCircle(centerX, centerY, radius, paint)
        super.dispatchDraw(canvas)
    }

}