package com.remax.visualnovel.extension

import com.remax.visualnovel.constant.AppStatus
import com.remax.visualnovel.utils.spannablex.utils.dp
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * Created by HJW on 2020/9/10
 */
fun String?.md5Encode(): String {
    if (this == null) {
        return ""
    }
    try {
        //获取md5加密对象
        val instance: MessageDigest = MessageDigest.getInstance("MD5")
        //对字符串加密，返回字节数组
        val digest: ByteArray = instance.digest(this.toByteArray())
        val sb: StringBuffer = StringBuffer()
        for (b in digest) {
            //获取低八位有效值
            val i: Int = b.toInt() and 0xff
            //将整数转化为16进制
            var hexString = Integer.toHexString(i)
            if (hexString.length < 2) {
                //如果是一位的话，补0
                hexString = "0$hexString"
            }
            sb.append(hexString)
        }
        return sb.toString()

    } catch (e: NoSuchAlgorithmException) {
        e.printStackTrace()
    }

    return ""
}

/**
 * 处理图片压缩
 *
 */
fun String?.toS3Url(wid: Int, hei: Int? = null, isDp: Boolean = true, isFill: Boolean = hei != null): String {
    if (isNullOrEmpty()) return ""
    return when {
        this.endsWith(".gif") -> {
            this
        }

        else -> {
            val resizeWid = if (isDp) wid.dp else wid
            val resizeHei = if (hei != null) {
                if (isDp) hei.dp else hei
            } else {
                resizeWid
            }
            "$this?x-oss-process=image/resize${if (isFill) ",m_fill" else ""},w_${resizeWid},h_${resizeHei}"
        }
    }
}

/**
 * 图片新增方向裁剪
 * 以宽为基准 w,1
 * 以高为基准 h,1
 */
fun String?.toCropS3Url(isWidth: Boolean, radio: Float) = "${this ?: ""}&m_crop=${if (isWidth) "w" else "h"},$radio"


// 正则表达式匹配 () ,包括中英文的，不考虑嵌套
fun String?.extractBrackets(): List<String> {
    val regex = Regex("(\\(.*?\\)|（.*?）)")
    // 按文本顺序提取所有匹配的括号对
    return regex.findAll(this ?: "").map { it.value }.toList()
}

/**
 * 获取云信的ID
 */
fun String?.getNimAccountId(isAI: Boolean) = this +
        if (isAI) {
            if (AppStatus.isProduct) "@r" else "@r@t"
        } else {
            if (AppStatus.isProduct) "@u" else "@u@t"
        }


/**
 * 检查长度
 */
fun String?.checkLength(minLength: Int, allowEmpty: Boolean = false): Boolean {
    return when {
        allowEmpty && this.isNullOrBlank() -> true
        minLength <= 0 && this.isNullOrBlank() -> false
        (this?.trim()?.length ?: 0) < minLength -> false
        else -> true
    }
}