package com.ydl.ydlcommon.utils.emoji

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import com.ydl.ydlcommon.utils.MoonUtil
import com.ydl.ydlcommon.utils.StringUtils

/**
 * editText 过滤emoji工具
 * Created by harvie on 2017/7/5 0005.
 */
object EmojiFilterUtil{

    fun filterEmoji(context: Context,editContent : EditText?){
        if (editContent!=null){
            val textWatcher = object : TextWatcher {
                private var start: Int = 0
                private var count: Int = 0

                override fun onTextChanged(arg0: CharSequence, start: Int, before: Int, count: Int) {
                    this.start = start
                    this.count = count
                    val editable = editContent.getText().toString()
                    val str = StringUtils.StringFilter(editable.toString())
                    if (editable != str) {
                        editContent.setText(str)
                        editContent.setSelection(str.length) //光标置后
                    }

                }

                override fun beforeTextChanged(arg0: CharSequence, start: Int, count: Int, after: Int) {}


                override fun afterTextChanged(arg0: Editable) {
                    editContent.removeTextChangedListener(this)
                    MoonUtil.replaceEmoticons(context, arg0, start, count)
                    var editEnd = editContent.getSelectionEnd()
                    editContent.removeTextChangedListener(this)
                    while (StringUtils.counterChars(arg0.toString()) > 5000 && editEnd > 0) {
                        arg0.delete(editEnd - 1, editEnd)
                        editEnd--
                    }
                    editContent.setSelection(editEnd)
                    editContent.addTextChangedListener(this)
                }

            }
            editContent.addTextChangedListener(textWatcher)
        }
    }

}