package com.adealink.weparty.commonui.imageview

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import com.adealink.frame.image.view.NetworkImageView

/**
 * fresco的view加载的GIF图片无法裁剪，在这里处理
 */
open class GIFImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0,
) : NetworkImageView(context, attrs, defStyleAttr) {

    private var roundPath: Path? = null

    @SuppressLint("DrawAllocation")
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (roundPath == null) {
            roundPath = Path()
        }
        if (hierarchy?.roundingParams?.roundAsCircle != true) {
            val radii = hierarchy?.roundingParams?.cornersRadii
            val rectF =
                RectF(0f, 0f, measuredWidth.toFloat(), measuredHeight.toFloat())
            if (radii != null) {
                roundPath?.addRoundRect(rectF, radii, Path.Direction.CW)
            }
        }

        if (hierarchy?.roundingParams?.roundAsCircle == true) {
            val radius =
                if (measuredHeight > measuredWidth) measuredWidth / 2 else measuredHeight / 2
            roundPath?.addCircle(
                measuredWidth.toFloat() / 2,
                measuredHeight.toFloat() / 2,
                radius.toFloat(),
                Path.Direction.CW
            )
        }
    }

    override fun onDraw(canvas: Canvas) {
        roundPath?.let { canvas.clipPath(it) }
        canvas.save()
        super.onDraw(canvas)
    }
}