package com.lukouguoji.module_base.adapter

import android.view.Gravity
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.lukouguoji.module_base.ktx.loge
import dev.utils.app.ViewUtils
import kotlin.math.roundToInt

// "\u3000"
private const val FullSpace = "\u3000"
private const val HalfSpace = "\u0020"
private const val QuarterSpace = "\u202F"

@BindingAdapter("completeSpace", "isFill", requireAll = false)
fun completeSpace(tv: TextView, count: Int, isFill: Boolean = true) {
    val s = StringBuilder()
    (1..count).forEach { _ ->
        s.append("一")
    }
    val measureText = tv.paint.measureText(s.toString())
    ViewUtils.setWidth(tv, measureText.roundToInt())

    if (isFill) {
        val text = tv.text.toString()
        val length = text.length

        if (length in 2 until count) {
            val sb = StringBuilder()
            // 计算需要补充的空格数量
            val cs = (count - text.length)
            // 无法被整除,则添加在最后
            val zc = (cs * 4) % (length - 1)
            if (zc != 0) {
                sb.append(text)
                for (i in 0 until cs) {
                    sb.append(FullSpace)
                }
            } else {
                val spaceValue = (cs * 4) / (length - 1)
                when (spaceValue) {
                    4 -> {
                        text.forEachIndexed { index, c ->
                            if (index > 0) {
                                sb.append(FullSpace)
                            }
                            sb.append(c)
                        }
                    }

                    else -> {
                        if (spaceValue > 4 && spaceValue % 4 == 0) {
                            val spaceCount = spaceValue / 4
                            text.forEachIndexed { index, c ->
                                if (index > 0) {
                                    for (i in 0 until spaceCount) {
                                        sb.append(FullSpace)
                                    }
                                }
                                sb.append(c)
                            }
                        } else {
                            sb.append(text)
                            for (i in 0 until cs) {
                                sb.append(FullSpace)
                            }
                        }
                    }
                }
            }
            tv.text = sb
        }
    }
}

@BindingAdapter("completeLetterSpace")
fun completeLetterSpace(tv: TextView, count: Int) {
    val s = StringBuilder()
    (1..count).forEach { _ ->
        s.append("A")
    }
    val measureText = tv.paint.measureText(s.toString())
    ViewUtils.setWidth(tv, measureText.roundToInt())
}