package com.iscs.bozzys.utils

/**
 * 获取角色名称
 */
fun List<String>.getRoleName(): String {
    LogUtil.d("RoleList", "$this")
    val roles = Storage.readRoleList()
    return if (this.contains("super_admin")) {
        roles.find { it.code == "super_admin" }?.name ?: ""
    } else if (this.contains("tenant_admin")) {
        roles.find { it.code == "tenant_admin" }?.name ?: ""
    } else if (this.contains("enSuperadmin")) {
        roles.find { it.code == "enSuperadmin" }?.name ?: ""
    } else if (this.contains("jtdrawer")) {
        roles.find { it.code == "jtdrawer" }?.name ?: ""
    } else if (this.contains("jtlocker")) {
        roles.find { it.code == "jtlocker" }?.name ?: ""
    } else if (this.contains("jtcolocker")) {
        roles.find { it.code == "jtcolocker" }?.name ?: ""
    } else {
        ""
    }
}

/**
 * 是否管理员
 */
fun List<String>?.isAdmin(): Boolean {
    if (this == null) return false
    return this.contains("super_admin") || this.contains("tenant_admin") || this.contains("enSuperadmin")
}

/**
 * 将字节数组转换为16进制字符串
 */
fun ByteArray.byteArrayToHexString(sep: String = ""): String {
    return joinToString(sep) { "%02X".format(it) }
}

/**
 * 16进制转自己数组
 */
fun String.hexToByteArray(): ByteArray {
    return this.chunked(2)
        .map { it.toInt(16).toByte() }
        .toByteArray()
}

/**
 * 将Int转为ByteArray数组
 */
fun Int.toByteArray(capability: Int = 2): ByteArray {
    val bytes = ByteArray(capability)
    for (i in 0 until capability) {
        // 大端模式
        // bytes[capability - i - 1] = ((this ushr (i * 8)) and 0xFF).toByte()
        // 小端模式
        bytes[i] = ((this ushr (i * 8)) and 0xFF).toByte()
    }
    return bytes
}

/**
 * CRC16 校验值
 * @return 两字节的校验值
 */
fun ByteArray.crc16(from: Int = 0, to: Int = size): ByteArray {
    val value = CRC16.crc16(this, from.coerceAtLeast(0), to.coerceAtMost(size))
    val c1 = (0xff00 and value shr 8).toByte()
    val c2 = (0xff and value).toByte()
    return byteArrayOf(c1, c2)
}