package com.casic.common.detector.gd.extensions

/**
 * ByteArray转Hex
 * */
fun ByteArray.toHex(): String {
    val hexArray = "0123456789ABCDEF".toCharArray()
    val hexChars = CharArray(this.size * 2)
    for (j in this.indices) {
        val v: Int = this[j].toInt() and 0xFF
        hexChars[j * 2] = hexArray[v ushr 4]
        hexChars[j * 2 + 1] = hexArray[v and 0x0F]
    }
    return String(hexChars)
}

fun ByteArray.handleSignalStrength(): String {
    //长度是单条数据整数倍
    var hex = this.toHex()
    if (this.size % 5 == 0) {
        for (i in this.indices step 5) {
            val temp = ByteArray(5)
            System.arraycopy(this, 0, temp, 0, 5)
            hex = temp.toHex()
        }
    } else {
        val indexArray = ArrayList<Int>()
        this.forEachIndexed { index, byte ->
            if (byte == 78.toByte()) {
                indexArray.add(index)
            }
        }

        //去掉最后一个index，数据肯定不满一帧
        for (i in 0 until indexArray.size - 1) {
            if (indexArray[i] % 5 == 0) {
                val temp = ByteArray(5)
                System.arraycopy(this, indexArray[i], temp, 0, 5)
                hex = temp.toHex()
            } else {
                //不是5倍数的index+5要小于整体数据长度，不然会越界
                if (indexArray[i] + 5 < this.size) {
                    val temp = ByteArray(5)
                    System.arraycopy(this, indexArray[i], temp, 0, 5)
                    hex = temp.toHex()
                }
            }
        }
    }
    return hex
}