package com.kaixed.kchat.utils;


import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;

import androidx.core.content.res.ResourcesCompat;

import com.kaixed.kchat.R;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: kaixed
 * @Date: 2024/5/30 19:47
 * @Description: TODO
 */
public class ImageSpanUtil {

    private static Map<String, Integer> emojiMap = new HashMap<>();
    private static final ImageSpanUtil INSTANCE = new ImageSpanUtil();

    private ImageSpanUtil() {
        emojiMap.put("[委屈]", R.drawable.emoji);
    }

    public ImageSpanUtil getInstance() {
        return INSTANCE;
    }

    public static SpannableString setEmojiSpan(Context context, String text, int textSize) {
        SpannableString spannableString = new SpannableString(text);

        String regexPattern = "\\[.*?\\]";

        Pattern pattern = Pattern.compile(regexPattern);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            // 获取匹配的起始和结束位置
            int start = matcher.start();
            int end = matcher.end();
            if (emojiMap.containsKey(matcher.group())) {
                Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), emojiMap.get(matcher.group()), null);
                assert drawable != null;
                drawable.setBounds(0, 0, textSize, textSize);
                ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                spannableString.setSpan(imageSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        }
        return spannableString;
    }

    public static void insertEmoji(Context context, Editable editable, int textSize, String emojiStr, int index) {
        // 插入表情符号到当前光标位置
        editable.insert(index, emojiStr);

        // 创建表情符号的ImageSpan
        if (emojiMap.containsKey(emojiStr)) {
            Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), emojiMap.get(emojiStr), null);
            if (drawable != null) {
                drawable.setBounds(0, 0, textSize, textSize);
                ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                // 应用ImageSpan到Editable对象
                editable.setSpan(imageSpan, index, index + emojiStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }


}