package com.adealink.weparty.commonui.widget.constrainlayout

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout

/**
 * 圆角约束布局
 * 参考实现项目：https://github.com/GcsSloop/rclayout
 */
class RoundCornerConstraintLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    ConstraintLayout(context, attrs, defStyleAttr) {

    var mRoundCornerConstraintLayoutHelper: RoundCornerConstraintLayoutHelper? = null

    init {
        mRoundCornerConstraintLayoutHelper = RoundCornerConstraintLayoutHelper().apply {
            initAttrs(context, attrs)
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mRoundCornerConstraintLayoutHelper?.onSizeChanged(this, w, h)
    }

    override fun dispatchDraw(canvas: Canvas) {
        canvas.saveLayer(mRoundCornerConstraintLayoutHelper?.mLayer, null, Canvas.ALL_SAVE_FLAG)
        super.dispatchDraw(canvas)
        mRoundCornerConstraintLayoutHelper?.onClipDraw(canvas)
        canvas.restore()
    }

    override fun draw(canvas: Canvas) {
        if (mRoundCornerConstraintLayoutHelper?.mClipBackground == true) {
            canvas.save()
            mRoundCornerConstraintLayoutHelper?.mClipPath?.let {
                canvas.clipPath(it)
            }
            super.draw(canvas)
            canvas.restore()
        } else {
            super.draw(canvas)
        }
    }

    fun setRadius(radius: Int) {
        mRoundCornerConstraintLayoutHelper?.apply {
            for (i in radii.indices) {
                radii[i] = radius.toFloat()
            }
            invalidate()
        }
    }

    fun setTopLeftRadius(topLeftRadius: Int) {
        mRoundCornerConstraintLayoutHelper?.apply {
            radii[0] = topLeftRadius.toFloat()
            radii[1] = topLeftRadius.toFloat()
            invalidate()
        }
    }

    fun setTopRightRadius(topRightRadius: Int) {
        mRoundCornerConstraintLayoutHelper?.apply {
            radii[2] = topRightRadius.toFloat()
            radii[3] = topRightRadius.toFloat()
            invalidate()
        }
    }

    fun setBottomLeftRadius(bottomLeftRadius: Int) {
        mRoundCornerConstraintLayoutHelper?.apply {
            radii[6] = bottomLeftRadius.toFloat()
            radii[7] = bottomLeftRadius.toFloat()
            invalidate()
        }
    }

    fun setBottomRightRadius(bottomRightRadius: Int) {
        mRoundCornerConstraintLayoutHelper?.apply {
            radii[4] = bottomRightRadius.toFloat()
            radii[5] = bottomRightRadius.toFloat()
            invalidate()
        }
    }

    override fun invalidate() {
        mRoundCornerConstraintLayoutHelper?.refreshRegion(this)
        super.invalidate()
    }
}