package com.kaixed.kchat.utils

import android.content.Context
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import androidx.core.content.res.ResourcesCompat
import com.kaixed.kchat.R
import java.util.regex.Pattern

/**
 * @Author: kaixed
 * @Date: 2024/10/24 22:12
 */

object ImageSpanUtil {

    private val emojiMap: MutableMap<String, Int> = hashMapOf("[委屈]" to R.drawable.emoji)

    fun setEmojiSpan(context: Context, text: String, textSize: Int): SpannableString {
        val spannableString = SpannableString(text)
        val regexPattern = "\\[.*?\\]"

        val pattern = Pattern.compile(regexPattern)
        val matcher = pattern.matcher(text)
        while (matcher.find()) {
            // 获取匹配的起始和结束位置
            val start = matcher.start()
            val end = matcher.end()
            val emojiResId = emojiMap[matcher.group()]
            if (emojiResId != null) {
                val drawable = ResourcesCompat.getDrawable(context.resources, emojiResId, null)
                drawable?.let {
                    val newSize = (textSize * 1.2).toInt()
                    it.setBounds(0, 0, newSize, newSize)
                    val centeredImageSpan = CenteredImageSpan(it)
                    val verticalAlignImageSpan = VerticalAlignImageSpan(it)
                    spannableString.setSpan(
                        verticalAlignImageSpan,
                        start,
                        end,
                        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                    )
                }
            }
        }
        return spannableString
    }

    fun insertEmoji(
        context: Context,
        editable: Editable,
        textSize: Int,
        emojiStr: String,
        index: Int
    ) {
        // 插入表情符号到当前光标位置
        editable.insert(index, emojiStr)

        // 创建表情符号的ImageSpan
        val emojiResId = emojiMap[emojiStr]
        if (emojiResId != null) {
            val drawable = ResourcesCompat.getDrawable(context.resources, emojiResId, null)
            drawable?.let {
                val newSize = (textSize * 1.2).toInt()
                it.setBounds(0, 0, newSize, newSize)
                val centeredImageSpan = CenteredImageSpan(it)
                editable.setSpan(
                    centeredImageSpan,
                    index,
                    index + emojiStr.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
    }
}
