package com.gh.gamecenter.common.view

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.text.style.ReplacementSpan
import androidx.annotation.Dimension
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.core.utils.DisplayUtils

class RoundStrokeBackgroundColorSpan(
    private val strokeColor: Int,
    private val textColor: Int,
    private val strokeWidth: Int = 2,
    @Dimension(unit = Dimension.PX)
    private val textSize: Int = 0
) : ReplacementSpan() {

    private var halfStrokeWidth = 0

    init {
        halfStrokeWidth = strokeWidth / 2
    }

    override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
        return paint.measureText(text, start, end).toInt()
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        val originalColor = paint.color
        val originalTextSize = paint.textSize

        paint.color = this.strokeColor
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = strokeWidth.toFloat()

        val fontMetrics = paint.fontMetrics

        // 当目标字体大小与原字体大小不一样时，需要先用目标字体大小测量字体宽度
        if (textSize != 0) {
            paint.textSize = textSize.toFloat()
        }
        val textWidth = paint.measureText(text, start, end).toInt()

        // 用原字体大小画椭圆
        paint.textSize = originalTextSize
        canvas.drawRoundRect(
            RectF(
                x + halfStrokeWidth,
                top.toFloat() + halfStrokeWidth,
                x + textWidth + halfStrokeWidth,
                top + fontMetrics.bottom - fontMetrics.top
            ),
            DisplayUtils.dip2px(HaloApp.getInstance(), 3f).toFloat(),
            DisplayUtils.dip2px(HaloApp.getInstance(), 3f).toFloat(),
            paint
        )

        paint.color = this.textColor
        paint.style = Paint.Style.FILL
        paint.strokeWidth = 0f

        // 用目标字体大小画字
        if (textSize != 0) {
            paint.textSize = textSize.toFloat()
        }
        canvas.drawText(text, start, end, x + halfStrokeWidth, y.toFloat() - strokeWidth, paint)

        paint.color = originalColor
    }
}
