package com.gh.download.simple

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.widget.ProgressBar
import androidx.annotation.Keep
import com.gh.gamecenter.core.utils.DisplayUtils

@Keep
class SimpleProgressView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
    ProgressBar(context, attrs, defStyle) {

    private var mWidth = 0
    private var mHalfWidth = 0
    private val mMatrix: Matrix
    private var mHalfTextWidth = 0F
    private val mTextPaint: Paint
    private var mTextSize = 0F
    private var mTextColor = Color.WHITE
    private var mText: String? = "打开"

    init {
        max = MAX_LENGTH
        mTextSize = DisplayUtils.sp2px(context, 12F).toFloat()
        mMatrix = Matrix()
        mTextPaint = Paint()
        mTextPaint.isAntiAlias = true
        mTextPaint.color = mTextColor
        mTextPaint.style = Paint.Style.FILL_AND_STROKE
        mTextPaint.typeface = Typeface.DEFAULT_BOLD
        mTextPaint.textSize = mTextSize
        mTextPaint.textAlign = Paint.Align.CENTER
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        mWidth = width
        mHalfWidth = mWidth / 2
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (mText != null) {
            setProgressByPixels(mWidth * progress / MAX_LENGTH)
            val fontMetrics = mTextPaint.fontMetricsInt
            val baseline = (height - fontMetrics.bottom - fontMetrics.top) / 2
            canvas.drawText(mText!!, mHalfWidth.toFloat(), baseline.toFloat(), mTextPaint)
        }
    }

    var text: String?
        get() = mText
        set(text) {
            mText = text
            postInvalidate()
        }

    fun setTextColor(color: Int) {
        mTextColor = color
        mTextPaint.color = color
    }

    fun setTextSize(size: Float) {
        mTextSize = size
        mTextPaint.textSize = size
    }

    private fun setProgressByPixels(pixels: Int) {
        if (pixels >= mHalfWidth - mHalfTextWidth) {
            mMatrix.setTranslate(pixels - (mHalfWidth - mHalfTextWidth), 0F)
        } else {
            mMatrix.setTranslate(0F, 0F)
        }
    }

    companion object {
        const val MAX_LENGTH = 100
    }

}