package com.gh.gamecenter.common.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.view.WindowManager
import android.widget.FrameLayout
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor

class GuideMaskLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : FrameLayout(context, attrs, defStyle) {
    /**
     * 高亮引导区域
     */
    val targetRect = RectF()

    /**
     * 蒙层区域
     */
    private val overlayRect = RectF()

    /**
     * 蒙层背景画笔
     */
    private val overlayPaint: Paint

    /**
     * 圆角大小
     */
    private var cornerRadius = 0

    /**
     * 挖空画笔
     */
    private val targetPaint: Paint

    /**
     * 挖空Bitmap
     */
    private var targetBitmap: Bitmap?

    /**
     * 挖空Canvas
     */
    private val targetCanvas: Canvas

    init {
        //自我绘制
        setWillNotDraw(false)

        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val displayMetrics = DisplayMetrics()
        wm.defaultDisplay.getRealMetrics(displayMetrics)
        val width = displayMetrics.widthPixels
        val height = displayMetrics.heightPixels
        overlayRect.set(0F, 0F, width.toFloat(), height.toFloat())
        targetBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        targetCanvas = Canvas(targetBitmap!!)
        overlayPaint = Paint()
        targetPaint = Paint()
        targetPaint.color = Color.TRANSPARENT
        targetPaint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.CLEAR))
        targetPaint.flags = Paint.ANTI_ALIAS_FLAG

        if (attrs != null) {
            val ta = context.obtainStyledAttributes(attrs, R.styleable.GuideMaskLayout)
            overlayPaint.color =
                ta.getColor(R.styleable.GuideMaskLayout_gml_mask_color, R.color.black_alpha_40.toColor(context))
            cornerRadius = ta.getDimensionPixelSize(
                R.styleable.GuideMaskLayout_gml_radius,
                4F.dip2px(context)
            )
            ta.recycle()
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        try {
            clearFocus()
            targetCanvas.setBitmap(null)
            targetBitmap = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        targetBitmap!!.eraseColor(Color.TRANSPARENT)
        targetCanvas.drawColor(overlayPaint.color)
        targetCanvas.drawRoundRect(
            targetRect,
            cornerRadius.toFloat(),
            cornerRadius.toFloat(),
            targetPaint
        )
        canvas.drawBitmap(targetBitmap!!, overlayRect.left, overlayRect.top, null)
    }
}