package llc.arma.ble.data.repository.extensions

import java.nio.ByteBuffer
import java.nio.ByteOrder

fun ByteArray.get2byteShortAt(): Int {
    val shorts = ShortArray(1)
    ByteBuffer.wrap(this).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()[shorts]
    return shorts[0].toInt()
}

fun ByteArray.get4byteUIntAt(idx: Int) =
    ((this[idx + 3].toUInt() and 0xFFu) shl 24) or
            ((this[idx + 2].toUInt() and 0xFFu) shl 16) or
            ((this[idx + 1].toUInt() and 0xFFu) shl 8) or
            (this[idx].toUInt() and 0xFFu)

fun ByteArray.get2byteUIntAt(idx: Int) =
    ((this[idx + 1].toUInt() and 0xFFu) shl 8) or
            (this[idx].toUInt() and 0xFFu)

fun UInt.to4ByteArrayInLittleEndian(): ByteArray =
    (3 downTo 0).map {
        (this shr (it * Byte.SIZE_BITS)).toByte()
    }.toByteArray()

@OptIn(ExperimentalUnsignedTypes::class)
fun UByteArray.toTemperature(): Float {

    val uShort = (this[0] + this[1] * 256u).toUShort()

    val result = if (uShort > Short.MAX_VALUE.toUShort()) {
        ((uShort.inv() + 1u).toFloat().unaryMinus()) / 100f
    } else {
        uShort.toFloat() / 100f
    }

    return result

}
