package com.gh.gamecenter.common.view.cropbox

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

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

    private var horizontalPadding = 0
    private var boxStyle: CropBoxStyle = CropBoxStyle.Rectangle(1F)
    private var drawer: CropBoxDrawer = CropBoxDrawer.RectangleDrawer()

    private val paint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            color = Color.parseColor("#CC000000")
        }
    }

    private val borderPaint by lazy {
        Paint().apply {
            style = Paint.Style.STROKE
            isAntiAlias = true
            setColor(Color.WHITE)
            strokeWidth = 0.5F.dip2px().toFloat()
        }
    }

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

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val rect = boxStyle.getRect(width, height, horizontalPadding)
        val layerId = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), paint, Canvas.ALL_SAVE_FLAG)

        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
        paint.xfermode = xFermode
        drawer.onDraw(rect, canvas, paint)
        paint.xfermode = null

        canvas.restoreToCount(layerId)

        // 绘制裁剪框边框
        drawer.onDrawDecoration(rect, canvas, borderPaint)
    }

    fun setHorizontalPaddingBoxStyle(horizontalPadding: Int, boxStyle: CropBoxStyle) {
        this.horizontalPadding = horizontalPadding
        this.boxStyle = boxStyle
        drawer = createDrawer(boxStyle)
    }

    private val cropBoxAnimator by lazy {
        CropBoxAnimator {
            paint.color = it
            postInvalidateOnAnimation()
        }
    }


    fun changeDragState(isDragging: Boolean) {
        cropBoxAnimator.changeDragState(isDragging)
    }

    private fun createDrawer(boxStyle: CropBoxStyle) = when (boxStyle) {
        is CropBoxStyle.Circle -> CropBoxDrawer.CircleDrawer()
        is CropBoxStyle.Rectangle -> CropBoxDrawer.RectangleDrawer()
    }

}