package com.tools.device.devcheck.custom

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import androidx.core.graphics.toColorInt

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

    private val barPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
    }

    private val inactiveColor = "#eeeeee".toColorInt()
    private val activeColor = "#1E8C29".toColorInt()

    private var strengthLevel: Int = 0
    private val maxBars = 5

    // 设置信号强度 (0-5)
    fun setStrength(level: Int) {
        strengthLevel = level.coerceIn(0, maxBars)
        invalidate() // 触发重绘
    }

    // 获取当前信号强度
    fun getStrength(): Int = strengthLevel

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

        val width = width.toFloat()
        val height = height.toFloat()

        // 计算每个柱状条的宽度和间距
        val barWidth = width / (maxBars * 2 - 1)
        val spacing = barWidth/4

        // 绘制5个柱状条
        for (i in 0 until maxBars) {
            // 确定柱状条的颜色
            val color = if (i < strengthLevel) activeColor else inactiveColor
            barPaint.color = color

            // 计算柱状条的位置和高度
            val left = i * (barWidth + spacing)
            val barHeight = height * (i + 1) / maxBars
            val top = height - barHeight
            val right = left + barWidth
            val bottom = height

            // 绘制圆角矩形柱状条
            val rect = RectF(left, top, right, bottom)
            val cornerRadius = barWidth / 4
            canvas.drawRoundRect(rect, cornerRadius, cornerRadius, barPaint)
        }
    }
}