package com.gh.gamecenter.common.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import androidx.cardview.widget.CardView
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.utils.dip2px

open class RadiusCardView : CardView {
    var topLeftRadius = 0f
    var topRightRadius = 0f
    var bottomLeftRadius = 0f
    var bottomRightRadius = 0f

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        radius = 0f
        val array = context.obtainStyledAttributes(attrs, R.styleable.RadiusCardView)
        topLeftRadius = array.getDimensionPixelSize(R.styleable.RadiusCardView_topLeftRadius, 0).toFloat()
        topRightRadius = array.getDimensionPixelSize(R.styleable.RadiusCardView_topRightRadius, 0).toFloat()
        bottomLeftRadius = array.getDimensionPixelSize(R.styleable.RadiusCardView_bottomLeftRadius, 0).toFloat()
        bottomRightRadius = array.getDimensionPixelSize(R.styleable.RadiusCardView_bottomRightRadius, 0).toFloat()
        background = ColorDrawable()
        array.recycle()
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        val path = Path()
        val rectF: RectF = getRectF()
        val radius = floatArrayOf(
            topLeftRadius,
            topLeftRadius,
            topRightRadius,
            topRightRadius,
            bottomLeftRadius,
            bottomLeftRadius,
            bottomLeftRadius,
            bottomLeftRadius
        )
        path.addRoundRect(rectF, radius, Path.Direction.CW)
        canvas.clipPath(path, Region.Op.INTERSECT)
        super.onDraw(canvas)
    }

    fun setRadiusPx(tLRadius: Float, tRRadius: Float, bLRadius: Float, bRRadius: Float) {
        topLeftRadius = tLRadius
        topRightRadius = tRRadius
        bottomLeftRadius = bLRadius
        bottomRightRadius = bRRadius
        invalidate()
    }

    fun setRadius(tLRadius: Float, tRRadius: Float, bLRadius: Float, bRRadius: Float) {
        setRadiusPx(
            tLRadius.dip2px().toFloat(),
            tRRadius.dip2px().toFloat(),
            bLRadius.dip2px().toFloat(),
            bRRadius.dip2px().toFloat()
        )
    }

    private fun getRectF(): RectF {
        val rect = Rect()
        getDrawingRect(rect)
        return RectF(rect)
    }
}