package com.gh.gamecenter.qa.questions.edit.tip

import android.content.Context
import android.text.Html
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AutoCompleteTextView
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.QuestionEditTitleSearchItemBinding
import com.gh.gamecenter.qa.entity.QuestionsIndexEntity
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager


/**
 * Created by khy on 3/05/18.
 */
class QuestionTitleTipAdapter(private val context: Context, title: AutoCompleteTextView, communityId: String?) :
    BaseAdapter(), Filterable {

    var questionList: MutableList<QuestionsIndexEntity> = ArrayList()
    var mTitleView = title
    var mCommunityId = communityId
    var mSearchKey: String? = null

    override fun getView(pos: Int, convertView: View?, parent: ViewGroup?): View {
        val view: View
        val binding: QuestionEditTitleSearchItemBinding
        if (convertView == null) {
            binding = QuestionEditTitleSearchItemBinding.inflate(LayoutInflater.from(context), convertView, false)
            view = binding.root
            view.tag = binding
        } else {
            view = convertView
            binding = view.tag as QuestionEditTitleSearchItemBinding
        }
        val entity = questionList[pos]
        binding.questionsEditIndexAnswerCount.text = "${entity.answerCount} 回答"
        binding.questionsEditIndexTitle.text = Html.fromHtml(replayKeyword(entity.title))
        view.setOnClickListener {
            context.startActivity(NewQuestionDetailActivity.getIntent(context, entity.id, "", "问题编辑-标题自动搜索"))
        }
        return view

    }

    private fun replayKeyword(title: String): String {
        var translationKey = escapeExprSpecialWord(mSearchKey)
        return if (TextUtils.isEmpty(translationKey)) title else title.replace(
            translationKey?.toRegex()!!,
            getHtmlKeyword()
        )
    }

    // 特殊符合转译
    private fun escapeExprSpecialWord(s: String?): String? {
        var keyword = s
        if (!keyword.isNullOrEmpty()) {
            val fbsArr = arrayOf("\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|")
            for (key in fbsArr) {
                if (keyword!!.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key)
                }
            }
        }
        return keyword
    }

    private fun getHtmlKeyword(): String {
        return "<font color=\"#ff4147\">$mSearchKey</font>"
    }

    override fun getItem(pos: Int): Any {
        return questionList[pos]
    }

    override fun getItemId(pos: Int): Long {
        return pos.toLong()
    }

    override fun getCount(): Int {
        return questionList.size
    }

    override fun getFilter(): Filter {
        return QuestionTitleFilter()
    }

    inner class QuestionTitleFilter : Filter() {

        override fun performFiltering(prefix: CharSequence?): FilterResults {
            val results = FilterResults()
            if (prefix.isNullOrBlank()) return results
            RetrofitManager
                .getInstance().api
                .getAskSearchByTitle(mCommunityId, prefix.toString(), 1)
                .subscribe(object : Response<List<QuestionsIndexEntity>>() {
                    override fun onResponse(response: List<QuestionsIndexEntity>?) {
                        results.values = response
                        results.count = response!!.size
                        mSearchKey = prefix.toString()
                    }
                })
            return results
        }

        override fun publishResults(constant: CharSequence?, results: FilterResults?) {
            if (results != null && results.count > 0) {
                questionList = results.values as ArrayList<QuestionsIndexEntity>
            } else {
                questionList.clear()
            }
            if (questionList.size > 2) {
                mTitleView.dropDownHeight = DisplayUtils.dip2px(context, 200F)
            } else {
                mTitleView.dropDownHeight = ViewGroup.LayoutParams.WRAP_CONTENT
            }
            notifyDataSetChanged()
        }

    }
}
