package com.remax.visualnovel.widget.ui.bannerindicator

import android.content.Context
import android.graphics.Canvas
import android.graphics.RectF
import android.util.AttributeSet
import com.remax.visualnovel.R
import com.remax.visualnovel.utils.spannablex.utils.dp
import com.remax.visualnovel.widget.uitoken.handleUIToken
import com.youth.banner.indicator.BaseIndicator
import kotlin.math.ceil

/**
 * Created by HJW on 2022/9/8
 */
class RectangleIndicator @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    BaseIndicator(context, attrs, defStyleAttr) {

    companion object {
        const val XSMALL = 1
        const val SMALL = 2
    }

    private val rectF = RectF()

    private val selectColor = context.handleUIToken(R.string.color_surface_white_normal)?.color ?: 0
    private val normalColor = context.handleUIToken(R.string.color_surface_white_disabled)?.color ?: 0

    private val radius = context.handleUIToken(R.string.radius_pill)?.size ?: 0f

    private var singleWidth = 4.dp.toFloat()
    private var viewHeight = 4.dp.toFloat()
    private var viewSpace = 3.dp.toFloat()

    init {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.RectangleIndicator)
        val type = ta.getInt(R.styleable.RectangleIndicator_rectangleSize, XSMALL)
        ta.recycle()
        when (type) {
            XSMALL -> {
                singleWidth = 4.dp.toFloat()
                viewHeight = 4.dp.toFloat()
                viewSpace = 3.dp.toFloat()
            }

            SMALL -> {
                singleWidth = 8.dp.toFloat()
                viewHeight = 8.dp.toFloat()
                viewSpace = 4.dp.toFloat()
            }
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val count = config.indicatorSize
        if (count <= 1) {
            return
        }
        //间距*（总数-1）+默认宽度*（总数-1）+选中宽度
        val space = viewSpace * (count - 1)
        val normal = singleWidth * count
        val wid = ceil(space + normal).toInt()
        setMeasuredDimension(wid, ceil(viewHeight).toInt())
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val count = config.indicatorSize
        if (count <= 1) {
            return
        }
        var left = 0f
        for (i in 0 until count) {
            mPaint.color = if (config.currentPosition == i) selectColor else normalColor
            val indicatorWidth = singleWidth
            rectF.set(left, 0f, left + indicatorWidth, viewHeight)
            left += indicatorWidth + viewSpace
            canvas.drawRoundRect(rectF, radius, radius, mPaint)
        }
    }
}