package com.abbidot.tracker.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R

/**
 *Created  by .yzq on 2024/3/11/011.
 * @link
 * @description:直播使用的蓝牙信号
 */
class MySignalView : View {
    private lateinit var mContext: Context
    private var mWidth = 0
    private var mHeight = 0
    private var mStrokeWidth = 0f
    private var mLineSpace = 0f

    private lateinit var mPaint: Paint
    private val mMaxValue = 4
    private var mValue = 0

    constructor(context: Context) : super(context) {
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context, attrs, defStyleAttr
    ) {
        init(context, attrs)
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(mWidth, mHeight)
        LogUtil.e("onMeasure  $widthMeasureSpec,$heightMeasureSpec")
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        mContext = context
//        initAttrs(context, attrs)

        //禁用硬件加速,防止返回到界面多次执行onDraw
        setLayerType(LAYER_TYPE_SOFTWARE, null)

        mWidth = AppUtils.dpToPx(24)
        mHeight = mWidth
        mStrokeWidth = AppUtils.dpToPx(2f)
        mLineSpace = (mWidth - mStrokeWidth * mMaxValue) / (mMaxValue - 1)

        mPaint = Paint().apply {
            color = ContextCompat.getColor(context, R.color.black)
            strokeWidth = mStrokeWidth
            strokeCap = Paint.Cap.ROUND
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.apply {
            startDraw(this)
        }
    }

    private fun startDraw(canvas: Canvas) {
        for (i in 1..mMaxValue) {
            mPaint.color = if (i > mValue) {
                ContextCompat.getColor(mContext, R.color.black15)
            } else {
                ContextCompat.getColor(mContext, R.color.black)
            }

            //需要减去1个像素
            val startX = (mStrokeWidth * i) + (mLineSpace * (i - 1)) - i
            val startY = mHeight - (mHeight * (i / 4f))
            canvas.drawLine(startX, startY, startX, mHeight.toFloat(), mPaint)
        }
    }

    fun setValue(value: Int) {
        mValue = if (value < 0) {
            0
        } else if (value > mMaxValue) {
            mMaxValue
        } else value
        invalidate()
    }
}