package com.convenient.android.common.extension

import android.os.Build
import android.text.Html
import android.text.Spanned
import com.convenient.android.common.utils.string.REGEX_EMAIL
import com.convenient.android.common.utils.string.REGEX_MOBILE_EXACT
import java.util.regex.Pattern

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/7/29
 * description: 字符串相关扩展类
 */

fun ByteArray.toHexString(): String {
    return joinToString(separator = "") { eachByte ->
        "%02x".format(eachByte)
    }.uppercase()
}

/**
 * 解码Hex字符串
 * @return 返回解码出的byteArray数组
 */
fun String.decodeHexString() : ByteArray {
    check(length % 2 == 0){

    }
    return chunked(2)
        .map {
            it.toInt(16).toByte()
        }.toByteArray()
}

/**
 * 判断是否匹配正则
 *
 * @param regex 正则表达式
 * @param input 要匹配的字符串
 * @return `true`: 匹配<br></br>`false`: 不匹配
 */
fun CharSequence?.isMatch(regex: String, input: CharSequence?): Boolean {
    return input != null && input.isNotEmpty() && Pattern.matches(regex, input)
}

/**
 * 是否是邮箱
 */
fun CharSequence?.isEmail(): Boolean {
    return isMatch(REGEX_EMAIL, this)
}

/**
 * 正则判断是否是邮箱
 */
fun CharSequence?.isPhone(phoneNumber : CharSequence) : Boolean{
    return isMatch(REGEX_MOBILE_EXACT, phoneNumber)
}

/**
 * 判断字符串是否是数字
 */
fun CharSequence.isNumber() : Boolean{
    try {
        this.toString().toInt()
    }catch (e : Exception){
        false
    }
    return true
}


fun String.fromHtml(): Spanned? {
    return when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
        else -> Html.fromHtml(this)
    }
}


