package com.develop.common.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View

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

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var defaultColor: Int = Color.RED
    private var progressColor: Int = Color.RED
    private var radius: Float = 10f
    private var progress: Float = 1.0f

    init {
        defaultColor = Color.parseColor("#CCA3A3A2")
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        radius = h / 2f
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        paint.color = defaultColor
        canvas.drawRoundRect(
            0f, 0f,
            width.toFloat(), height.toFloat(),
            radius, radius, paint
        )
        if (progress != 1.0f) {
            canvas.clipRect(0, 0, (width * progress).toInt(), height)
        }
        paint.color = progressColor
        canvas.drawRoundRect(
            0f, 0f,
            width.toFloat(), height.toFloat(),
            radius, radius, paint
        )
    }

    fun setProgress(progress: Float) {
        var setting = progress
        if (setting < 0) {
            setting = 0f
        }
        if (setting > 1.0f) {
            setting = 1.0f
        }
        this.progress = setting
        invalidate()
    }

    fun setButtonColor(color: Int) {
        progressColor = color
        invalidate()
    }
}