package com.dumpster.cleaner.ui.batteryinfo

import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.AbsoluteSizeSpan
import android.text.style.StyleSpan
import android.view.ViewGroup
import com.dumpster.cleaner.R
import com.dumpster.cleaner.databinding.ItemBatteryHeadBinding
import com.dumpster.cleaner.ui.adapter.CommonViewHolder
import com.dumpster.cleaner.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter

class BatteryHead(
    val hour: Int,
    val min: Int,
)

class BatteryHeadAdapter : BaseQuickAdapter<BatteryHead, CommonViewHolder>() {

    override fun onBindViewHolder(
        holder: CommonViewHolder,
        position: Int,
        item: BatteryHead?
    ) {
        item ?: return
        val binding = ItemBatteryHeadBinding.bind(holder.itemView)

        val h = if (item.hour < 10) "0${item.hour}" else item.hour.toString()
        val min = if (item.min < 10) "0${item.min}" else item.min.toString()
        val text1 = "$h h "
        val text2 = "$min m"

        binding.tvTime.text = buildSpannableString(text1, h)
        binding.tvTime.append(buildSpannableString(text2, min))
    }

    override fun onCreateViewHolder(
        context: Context,
        parent: ViewGroup,
        viewType: Int
    ): CommonViewHolder {
        return CommonViewHolder(R.layout.item_battery_head.inflate(parent))
    }

    fun buildSpannableString(fullString: String, tagString: String): SpannableString {
        val spannableString = SpannableString(fullString)
        val start = fullString.indexOf(tagString)
        val end = start + tagString.length

        spannableString.setSpan(
            StyleSpan(Typeface.BOLD),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannableString.setSpan(
            AbsoluteSizeSpan(32, true),
            start, end,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        return spannableString
    }
}