package com.gh.gamecenter.video.poster

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.gh.gamecenter.common.utils.dip2px

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

    private var isLight = false

    private var leftTopCorner = 0F
    private var rightTopCorner = 0F
    private var leftBottomCorner = 0F
    private var rightBottomCorner = 0F

    private val paint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
        }
    }

    val defaultColor = Color.parseColor("#40000000")
    val lightColor = Color.parseColor("#000000")

    private val xFermode by lazy {
        PorterDuffXfermode(PorterDuff.Mode.CLEAR)
    }

    private val rectF = RectF()
    private var path = Path()

    fun setCorners(leftTop: Float, rightTop: Float, rightBottom: Float, leftBottom: Float) {
        leftTopCorner = leftTop
        rightTopCorner = rightTop
        rightBottomCorner = rightBottom
        leftBottomCorner = leftBottom
        postInvalidateOnAnimation()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        rectF.set(0F, 0F, w.toFloat(), h.toFloat())
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (isLight) {
            paint.color = lightColor
            val layerId = canvas.saveLayerAlpha(rectF, 64)

            drawBackground(canvas)
            paint.xfermode = xFermode
            canvas.drawRoundRect(rectF, 4F.dip2px().toFloat(), 4F.dip2px().toFloat(), paint)
            paint.xfermode = null
            canvas.restoreToCount(layerId)
        } else {
            paint.color = defaultColor
            drawBackground(canvas)
        }
    }

    private fun drawBackground(canvas: Canvas) {
        path.reset()
        val radii = floatArrayOf(
            leftTopCorner,
            leftTopCorner,
            rightTopCorner,
            rightTopCorner,
            rightBottomCorner,
            rightBottomCorner,
            leftBottomCorner,
            leftBottomCorner,
        )
        path.addRoundRect(rectF, radii, Path.Direction.CW)
        canvas.drawPath(path, paint)
    }

    fun setLight(isLight: Boolean) {
        this.isLight = isLight
        postInvalidateOnAnimation()
    }
}