package com.base.scanqrclear.luma

import android.content.Context
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

object Utils {

    fun getFormatSize(bytes: Number): String {
        val value: Double
        val unit: String
        if (bytes.toDouble() < 1024) {
            value = bytes.toDouble()
            unit = " B"
        } else if (bytes.toDouble() < 1024 * 1024) {
            value = bytes.toDouble() / 1024
            unit = " KB"
        } else if (bytes.toDouble() < 1024 * 1024 * 1024) {
            value = bytes.toDouble() / (1024 * 1024)
            unit = " MB"
        } else {
            value = bytes.toDouble() / (1024 * 1024 * 1024)
            unit = " GB"
        }
        val formattedNumber = String.format("%.2f", value)
        return formattedNumber + unit
    }

    fun getSize(bytes: Long): String {
        if (bytes == 0.toLong()) return "0 B"
        val value: Double
        val unit: String
        if (bytes.toDouble() < 1024) {
            value = bytes.toDouble()
            unit = " B"
        } else if (bytes.toDouble() < 1024 * 1024) {
            value = bytes.toDouble() / 1024
            unit = " KB"
        } else if (bytes.toDouble() < 1024 * 1024 * 1024) {
            value = bytes.toDouble() / (1024 * 1024)
            unit = " MB"
        } else {
            value = bytes.toDouble() / (1024 * 1024 * 1024)
            unit = " GB"
        }
        val formattedNumber = String.format("%.1f", value)
        return formattedNumber + unit
    }

    fun getSizeArray(bytes: Long): Array<String> {
        val value = getSize(bytes)
        val size = value.substring(0, value.indexOf(" "))
        val unit = value.substring(value.indexOf(" ") + 1)
        return arrayOf(size, unit)
    }

    fun Long.toDateString(): String {
        val formatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        return formatter.format(Date(this))
    }

    fun Context.toDate(): String {
        val formatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        return formatter.format(Date())
    }

    fun getCurrentMinute(): Int {
        val calendar = Calendar.getInstance()
        return calendar.get(Calendar.MINUTE)
    }

    fun calculate(dividend: Int, divisor: Int): String {
        val bigDecimalDividend = BigDecimal(dividend)
        val bigDecimalDivisor = BigDecimal(divisor)
        // 执行除法操作，并保留一位小数，不四舍五入
        val result = bigDecimalDividend.divide(bigDecimalDivisor, 1, RoundingMode.DOWN)
        // 将结果转换回Double
        return result.toString()
    }
}