package com.adealink.weparty.commonui.text

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.adealink.frame.aab.util.getCompatColor
import com.adealink.weparty.R

/**
 * 可设置文字描边的TextView
 * 默认文字描边颜色 color_app_main
 */
open class StrokeTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatTextView(context, attrs) {
    var strokeWidth: Float = 0f
        set(value) {
            field = value
            invalidate()
        }
    var strokeColor: Int = 0
        set(value) {
            field = value
            invalidate()
        }
    var strokeColorList: ColorStateList? = null
        set(value) {
            field = value
            invalidate()
        }
    private var isDrawing: Boolean = false

    init {
        initAttrs(context, attrs)
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        if (isInEditMode) {
            return
        }
        context.theme.obtainStyledAttributes(
            attrs,
            R.styleable.StrokeTextView,
            0, 0
        ).apply {
            strokeColor = getInt(
                R.styleable.StrokeTextView_strokeColor,
                getCompatColor(R.color.color_app_main)
            )
            strokeColorList = getColorStateList(
                R.styleable.StrokeTextView_strokeColorList
            )
            strokeWidth = getDimension(R.styleable.StrokeTextView_strokeWidth, 0f)
        }
    }

    override fun onDraw(canvas: Canvas) {
        if (strokeWidth <= 0) {
            super.onDraw(canvas)
            return
        }
        isDrawing = true
        val originColor = currentTextColor
        val originColors = textColors
        val originShader = paint.shader
        //描边
        if (strokeColorList != null) {
            setTextColor(strokeColorList)
        } else {
            setTextColor(strokeColor)
        }
        paint.strokeWidth = strokeWidth
        paint.style = Paint.Style.STROKE
        paint.isFakeBoldText = true
        paint.shader = null
        super.onDraw(canvas)

        //文字
        if (originColors != null) {
            setTextColor(originColors)
        } else {
            setTextColor(originColor)
        }
        paint.strokeWidth = 0f
        paint.style = Paint.Style.FILL
        paint.isFakeBoldText = false
        paint.shader = originShader
        super.onDraw(canvas)
        isDrawing = false
    }

    override fun invalidate() {
        if (isDrawing) {
            return
        }
        super.invalidate()
    }
}