package aicare.net.cn.sdk.ailinksdkdemoandroid.utils

import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.also
import kotlin.collections.copyOfRange
import kotlin.collections.joinToString
import kotlin.text.format
import kotlin.text.substring
import kotlin.text.toInt

/**
 * @author suzy
 * @date 2025/2/17 12:09
 **/
fun Long.toByteArray(): ByteArray {
    val buffer = ByteBuffer.allocate(8) // `Long` 类型占用 8 字节
    buffer.order(ByteOrder.BIG_ENDIAN) // 设置大端序
    buffer.putLong(this) // 将 `Long` 类型的时间戳放入缓冲区

    val byteArray = buffer.array()

    // 获取前 4 字节，即将 8 字节的时间戳截取成 4 字节（大端序）
    return byteArray.copyOfRange(4, byteArray.size)
}

fun ByteArray.toHexString(separator: String = ", "): String {
    return this.joinToString(separator) { "%02X".format(it) }
}

fun ByteArray.formatMac() = toHexString(":")

fun String.parseMacToByteArray(): ByteArray {
    // 预编译正则表达式（提升性能）
    require(Regex("^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$").matches(this)) {
        "Invalid MAC format: must match 'XX:XX:XX:XX:XX:XX'"
    }

    return ByteArray(6).also { bytes ->
        var index = 0
        var pos = 0
        while (index < 6) {
            bytes[index++] = substring(pos, pos + 2).toInt(16).toByte()
            pos += 3 // 跳过':'分隔符
        }
    }
}

fun ByteArray.toLong(): Long {
    require(this.size == 4) { "ByteArray must be exactly 4 bytes long" }

    val buffer = ByteBuffer.wrap(this)
    buffer.order(ByteOrder.BIG_ENDIAN)
    return buffer.int.toLong()
}

fun ByteArray.toAltitudeInt(): Int {
    require(this.size == 2) { "Input must be 2 bytes" }

    val value = ((this[0].toInt() and 0xFF) shl 8) or (this[1].toInt() and 0xFF)
    val isNegative = (value and 0x8000) != 0
    val absValue = value and 0x7FFF // 取低 15 位

    return if (isNegative) -absValue else absValue
}

fun Int.toByteArray(): ByteArray {
    val buffer = ByteBuffer.allocate(2)
    buffer.order(ByteOrder.BIG_ENDIAN)  // 使用大端序
    buffer.putShort(this.toShort())  // 将 Int 转换为 short 类型（2 字节）
    return buffer.array()
}

fun Int.toAltitudeBytes(): ByteArray {
    val altitude = this
    require(altitude in -32767..32767) { "Altitude must be in [-32767, 32767]" }

    val isNegative = altitude < 0
    val absValue = if (isNegative) -altitude else altitude

    // 构造 16 位数值（bit15=符号位，bit0~14=数值）
    val value = if (isNegative) absValue or 0x8000 else absValue

    // 转换为大端序 2 字节
    return byteArrayOf(
        (value shr 8).toByte(), // 高字节
        value.toByte()          // 低字节
    )
}

fun ByteArray.toInt(): Int {
    require(this.size == 2) { "ByteArray must be of size 2" } // 检查数组长度
    val buffer = ByteBuffer.wrap(this)
    buffer.order(ByteOrder.BIG_ENDIAN)  // 使用大端序
    val unsignedShort = buffer.short.toInt() and 0xFFFF
    return unsignedShort         // 将 short 转换为 int
}


fun Byte.toUnsignedInt(): Int = this.toInt() and 0xFF


