package com.ydl.confide.home

import android.content.Context
import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import com.ydl.confide.R
import com.ydl.confide.home.constants.FinalString
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import kotlinx.android.synthetic.main.confide_search_activity.*


class ConfideSearchActivity : BaseActivity() {



    override fun initDataAndEvent() {
        val keyWord = intent.getStringExtra(FinalString.CONFIDE_SEARCH_KEY_WORD)
        if (!TextUtils.isEmpty(keyWord)){
            etSearch?.setText(keyWord)
            iv_delete_icon.visibility = View.VISIBLE
        }

        etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val keyword = etSearch!!.text.trim().toString()
                //埋点
                ActionCountUtils.record("listen_counselor_list_page","listen_counselor_list_search_click",keyword)
                val intent = Intent()
                intent.putExtra(FinalString.CONFIDE_SEARCH_KEY_WORD, keyword)
                setResult(RESULT_OK,intent)
                finish()
            }
            true
        }

        findViewById<TextView>(R.id.tv_search_cancle).setOnClickListener {
            setResult(RESULT_OK)
            finish()
        }

        if (etSearch.requestFocus()) {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            val isShowing = imm.showSoftInput(etSearch, InputMethodManager.SHOW_IMPLICIT)
            if (!isShowing) {
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
            }
        }

        etSearch.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (TextUtils.isEmpty(s)) {
                    iv_delete_icon.visibility = View.INVISIBLE
                } else {
                    iv_delete_icon.visibility = View.VISIBLE
                }

            }

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

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })

        iv_delete_icon.setOnClickListener {
            etSearch.setText("")
        }
    }

    override fun layoutResId(): Int {
        return R.layout.confide_search_activity
    }


}