package com.bokecc.livemodule.live.chat.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.widget.EditText;

import com.bokecc.livemodule.R;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.pojo.CustomEmoji;
import com.bokecc.sdk.mobile.live.replay.DWLiveReplay;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmojiUtil {

    public static final Integer[] imgs = new Integer[]{
            R.drawable.em2_01, R.drawable.em2_02, R.drawable.em2_03, R.drawable.em2_04, R.drawable.em2_05, R.drawable.em2_06,
            R.drawable.em2_07, R.drawable.em2_08, R.drawable.em2_09, R.drawable.em2_10, R.drawable.em2_11, R.drawable.em2_12,
            R.drawable.em2_13, R.drawable.em2_14, R.drawable.em2_15, R.drawable.em2_16, R.drawable.em2_17, R.drawable.em2_18,
            R.drawable.em2_19, R.drawable.em2_20, R.drawable.em2_del
    };

    public static String[] imgNames = new String[]{
            "[em2_01]", "[em2_02]", "[em2_03]", "[em2_04]", "[em2_05]", "[em2_06]", "[em2_07]", "[em2_08]", "[em2_09]", "[em2_10]",
            "[em2_11]", "[em2_12]", "[em2_13]", "[em2_14]", "[em2_15]", "[em2_16]", "[em2_17]", "[em2_18]", "[em2_19]", "[em2_20]",
    };

    private static List<String> imgNamesList;

    static {
        imgNamesList = Arrays.asList(imgNames);
    }

    public static Pattern pattern = Pattern.compile("\\[em2_[0-2][0-9]\\]");

    public static Pattern patternCustom = Pattern.compile("\\[\\S*?\\]");

    public static SpannableString parseFaceMsg(Context context, SpannableString faceMsg) {
        return parseFaceMsg(context, faceMsg, true);
    }

    public static SpannableString parseFaceMsg(Context context, SpannableString faceMsg, boolean isLive) {
        Matcher m = pattern.matcher(faceMsg.toString());
        int size = DensityUtil.dp2px(context, 20);
        int margin = DensityUtil.dp2px(context, 2);
        while (m.find()) {
            String imgStr = m.group();
            int imgStrIndex = imgNamesList.indexOf(imgStr);
            if (imgStrIndex != -1) {
                Bitmap imgBitmap = BitmapFactory.decodeResource(context.getResources(), imgs[imgStrIndex]);
                imgBitmap = ThumbnailUtils.extractThumbnail(imgBitmap, size, size);
                VerticalImageSpan imgSpan = new VerticalImageSpan(context, imgBitmap, margin, margin);
                faceMsg.setSpan(imgSpan, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        ArrayList<CustomEmoji> customEmojis;
        if (isLive) {
            customEmojis = DWLive.getInstance().getCustomEmojis();
        } else {
            customEmojis = DWLiveReplay.getInstance().getCustomEmojis();
        }
        if (customEmojis != null && !customEmojis.isEmpty()) {
            HashMap<String, String> emojiMap = new HashMap<>();
            for (CustomEmoji customEmoji : customEmojis) {
                if (!TextUtils.isEmpty(customEmoji.getName()) && !TextUtils.isEmpty(customEmoji.getImg())) {
                    emojiMap.put(customEmoji.getName(), customEmoji.getImg());
                }
            }
            Matcher m1 = patternCustom.matcher(faceMsg.toString());
            while (m1.find()) {
                String imgStr = m1.group();
                String filePath = emojiMap.get(imgStr);
                if (!TextUtils.isEmpty(filePath)) {
                    Bitmap bitmap = decodeBitmap(filePath, size, size);
                    if (bitmap != null) {
                        VerticalImageSpan imgSpan = new VerticalImageSpan(context, bitmap, margin, margin);
                        faceMsg.setSpan(imgSpan, m1.start(), m1.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
            }
        }
        return faceMsg;
    }

    public static void deleteInputOne(EditText mInput) {
        deleteInputOne(mInput, true);
    }

    public static void deleteInputOne(EditText mInput, boolean isLive) {
        Editable editable = mInput.getText();
        int length = editable.length();
        if (length <= 0) {
            return;
        }
        int arrowPosition = mInput.getSelectionStart();
        if (arrowPosition == 0) {
            return;
        }
        String subString = editable.toString().substring(0, arrowPosition);
        if ("]".equals(subString.substring(subString.length() - 1))) {
            int i = subString.lastIndexOf("[");
            String emojiEmoji = subString.substring(i);
            if (isInCustomEmojiList(emojiEmoji, isLive)) {
                editable.delete(arrowPosition - emojiEmoji.length(), arrowPosition);
            } else {
                int imgIndex = subString.lastIndexOf("[em2_");
                if (imgIndex != -1) {
                    if ((imgIndex + 8) == arrowPosition) {
                        if (EmojiUtil.pattern.matcher(editable.toString().substring(imgIndex, imgIndex + 8)).find()) {
                            editable.delete(arrowPosition - 8, arrowPosition);
                        } else {
                            editable.delete(arrowPosition - 1, arrowPosition);
                        }
                    } else {
                        editable.delete(arrowPosition - 1, arrowPosition);
                    }
                } else {
                    editable.delete(arrowPosition - 1, arrowPosition);
                }
            }
        } else {
            editable.delete(arrowPosition - 1, arrowPosition);
        }
    }

    private static boolean isInCustomEmojiList(String emojiEmoji, boolean isLive) {
        ArrayList<CustomEmoji> customEmojis;
        if (isLive) {
            customEmojis = DWLive.getInstance().getCustomEmojis();
        } else {
            customEmojis = DWLiveReplay.getInstance().getCustomEmojis();
        }
        if (customEmojis != null && !customEmojis.isEmpty()) {
            for (CustomEmoji customEmoji : customEmojis) {
                String name = customEmoji.getName();
                if (!TextUtils.isEmpty(name) && emojiEmoji.equals(name)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void addEmoji(Context context, EditText mInput, int position) {
        String emojiStr = EmojiUtil.imgNames[position];
        int index = mInput.getSelectionStart();
        String content = mInput.getText().toString();
        String pre = content.substring(0, index);
        String next = content.substring(index, content.length());
        SpannableString ss = new SpannableString(pre + emojiStr + next);
        mInput.setText(parseFaceMsg(context, ss));
        mInput.setSelection(index + emojiStr.length());
    }

    public static void changeTextToEmoji(Context context, EditText mInput, String content) {
        SpannableString ss = new SpannableString(content);
        mInput.setText(parseFaceMsg(context, ss));
    }

    public static void addEmoji(Context context, EditText mInput, String name) {
        int index = mInput.getSelectionStart();
        String content = mInput.getText().toString();
        String pre = content.substring(0, index);
        String next = content.substring(index);
        mInput.getText();
        SpannableString ss = new SpannableString(pre + name + next);
        mInput.setText(parseFaceMsg(context, ss));
        mInput.setSelection(index + name.length());
    }

    public static Bitmap decodeBitmap(String filePath, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            int heightRatio = Math.round((float) height / (float) reqHeight);
            int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = Math.min(heightRatio, widthRatio);
        }
        return inSampleSize;
    }
}
