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

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import com.remax.visualnovel.R
import com.remax.visualnovel.extension.getTextFontTypeface
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 NumberIndicator @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    BaseIndicator(context, attrs, defStyleAttr) {

    private val rectF = RectF()

    private val textFont = context.handleUIToken(R.string.txt_label_s)?.textFont
    private val textColor = context.handleUIToken(R.string.color_txt_primary_normal)?.color ?: 0

    private val bgColor = context.handleUIToken(R.string.color_surface_element_disabled)?.color ?: 0

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

    private val viewHeight = 24.dp.toFloat()
    private var viewWidth = 0f

    init {
        mPaint.run {
            textFont?.let {
                typeface = context.getTextFontTypeface(it.typeFace)
                textSize = it.textFontSize
            }
            textAlign = Paint.Align.CENTER
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val count = config.indicatorSize
        if (count <= 1) {
            return
        }
        viewWidth = mPaint.measureText("$count/$count") + 16.dp
        setMeasuredDimension(ceil(viewWidth).toInt(), ceil(viewHeight).toInt())
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val count = config.indicatorSize
        if (count <= 1) {
            return
        }
        val content = "${config.currentPosition + 1}/$count"
        rectF.set(0f, 0f, viewWidth, viewHeight)
        mPaint.color = bgColor
        canvas.drawRoundRect(rectF, radius, radius, mPaint)
        mPaint.color = textColor
        val fontMetrics = mPaint.fontMetrics
        val distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
        val baseline = rectF.centerY() + distance * 1.5f
        canvas.drawText(content, rectF.centerX(), baseline, mPaint)
    }
}