package com.adealink.weparty.util

object UnitUtil {

    const val THOUSAND = 1000
    const val TEN_THOUSAND = 10000
    const val MILLION = 1000000

    fun changeUnit(score: Int): String {
        return when {
            score < THOUSAND -> score.toString()
            score < TEN_THOUSAND -> "%.2fK".format(score.toDouble() / THOUSAND)
            score < MILLION -> "%.2fK".format(score.toDouble() / THOUSAND)
            else -> "%.2fM".format(score.toDouble() / MILLION)
        }
    }

    /**
     * @param size 单位:Byte
     */
    fun formatByte(size: Long): String {
        var sizeFloat = size.toFloat()
        var suffix: String? = null

        if (size >= 1024) {
            suffix = "KB"
            sizeFloat /= 1024
            if (sizeFloat >= 1024) {
                suffix = "MB"
                sizeFloat /= 1024
                if (sizeFloat >= 1024) {
                    suffix = "GB"
                    sizeFloat /= 1024
                }
            }
        }

        val resultBuffer = StringBuilder(sizeFloat.toString())
        val commaOffset = resultBuffer.indexOf(".")
        if (commaOffset >= 0) {
            val decimalPoints = resultBuffer.length - commaOffset - 1
            if (decimalPoints > 2) {
                resultBuffer.setLength(commaOffset + 3)
            }
        }

        if (suffix != null) resultBuffer.append(suffix)
        return resultBuffer.toString()
    }
}