/*
 * Lunar Launcher
 * Copyright (C) 2022 Md Rasel Hossain
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package rasel.lunar.launcher.apps

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import io.realm.kotlin.ext.query
import io.realm.kotlin.query.RealmResults
import io.realm.kotlin.query.Sort
import rasel.lunar.launcher.BuildConfig
import rasel.lunar.launcher.CommadCallabck
import rasel.lunar.launcher.LauncherActivity
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.databinding.AppDrawerBinding
import rasel.lunar.launcher.helpers.Constants.Companion.KEY_APPS_COUNT
import rasel.lunar.launcher.helpers.Constants.Companion.KEY_APPS_LAYOUT
import rasel.lunar.launcher.helpers.Constants.Companion.PREFS_APP_NAMES
import rasel.lunar.launcher.helpers.Constants.Companion.PREFS_SETTINGS
import rasel.lunar.launcher.model.AppInfo
import rasel.lunar.launcher.utils.BLog
import rasel.lunar.launcher.utils.JamoUtils
import rasel.lunar.launcher.workers.WorkersDb
import java.net.URLEncoder
import java.text.Normalizer
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern


internal class AppDrawer : Fragment() {

    private lateinit var binding: AppDrawerBinding
    private var layoutType: Int = 0
    //    private var isSearchShown: Boolean = false
    private var isKeyboardShowing: Boolean = false

    companion object {
        private var packageManager: PackageManager? = null
        private var appsAdapter: AppsAdapter? = null
        private var contactAdapter : ContactAdapter? = null
        private var packageList = mutableListOf<AppInfo>()
        @JvmStatic var settingsPrefs: SharedPreferences? = null
        @JvmStatic var appNamesPrefs: SharedPreferences? = null


        fun appName(resolver: ResolveInfo): String {
            return resolver.loadLabel(packageManager).toString().apply {
                appNamesPrefs?.edit()?.putString(resolver.activityInfo.packageName, this)?.apply()
            }
        }

        fun getCategory(category : Int) : String {
            return when(category) {
                ApplicationInfo.CATEGORY_UNDEFINED -> "UNDEFINED"
                ApplicationInfo.CATEGORY_GAME -> "GAME"
                ApplicationInfo.CATEGORY_AUDIO -> "AUDIO"
                ApplicationInfo.CATEGORY_VIDEO -> "VIDEO"
                ApplicationInfo.CATEGORY_IMAGE -> "IMAGE"
                ApplicationInfo.CATEGORY_SOCIAL -> "SOCIAL"
                ApplicationInfo.CATEGORY_NEWS -> "NEWS"
                ApplicationInfo.CATEGORY_MAPS -> "MAPS"
                ApplicationInfo.CATEGORY_PRODUCTIVITY -> "PRODUCTIVITY"
                ApplicationInfo.CATEGORY_ACCESSIBILITY -> "ACCESSIBILITY"
                else -> {"UNKNOWN"}
            }
        }

    }
    fun getInputText() =  binding.searchInput.text.toString()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = AppDrawerBinding.inflate(inflater, container, false)

        settingsPrefs = requireContext().getSharedPreferences(PREFS_SETTINGS, 0)
        appNamesPrefs = requireContext().getSharedPreferences(PREFS_APP_NAMES, 0)
        layoutType = settingsPrefs!!.getInt(KEY_APPS_LAYOUT, 0)
        packageManager = lActivity?.packageManager
        appsAdapter = AppsAdapter(layoutType, packageManager!!, childFragmentManager, binding.appsCount)
        contactAdapter = ContactAdapter(packageManager!!, childFragmentManager)

        binding.appsCount.visibility = if (settingsPrefs!!.getBoolean(KEY_APPS_COUNT, true)) VISIBLE else GONE
        binding.searchNmap.setOnClickListener {
            openSearchApps("nmap://search?query=${getInputText()}&appname=${BuildConfig.APPLICATION_ID}","com.nhn.android.nmap")
        }
        binding.searchYoutube.setOnClickListener {
            openSearchApps("https://www.youtube.com/results?search_query=${getInputText()}","com.google.android.youtube")
        }
        binding.searchGoogleMap.setOnClickListener {
            openSearchApps("geo:0,0?q=${getInputText()}","com.google.android.apps.maps")
        }
        binding.searchGoogle.setOnClickListener {
            openSearchApps("https://www.google.com/search?q=${getInputText()}","com.android.chrome")
        }
        binding.searchTmap.setOnClickListener {
            openSearchApps("tmap://search?name=${getInputText()}","com.skt.tmap.ku")

        }
        binding.searchNaver.setOnClickListener {
            openSearchApps("https://search.naver.com/search.naver?where=nexearch&query=${getInputText()}", "com.nhn.android.search")
        }
        binding.searchDuckduckgo.setOnClickListener {
            openSearchApps("https://duckduckgo.com/?t=h_&q=${getInputText()}","com.duckduckgo.mobile.android")
        }
        binding.searchNamuwiki.setOnClickListener {
            openSearchApps("https://namu.wiki/Search?q=${getInputText()}")
        }

        binding.searchTranslate.setOnClickListener {
            openSearchApps("https://translate.google.com/?hl=ko&sl=ko&tl=en&text=${getInputText()}&op=translate","com.android.chrome")
        }
        binding.searchStore.setOnClickListener {
            openSearchApps("market://search?q=${getInputText()}")
        }
        binding.runSend.setOnClickListener {
            sendMsg()
        }
        binding.runTelegram.setOnClickListener {
            sendMsg("tg://msg?text=${getInputText()}&to=","org.telegram.messenger")
        }
        binding.runKatalk.setOnClickListener {
            sendMsg(pkg = "com.kakao.talk")
        }

        binding.runKatalkT.setOnClickListener{
            openSearchApps("kakaot://taxi?dest_lat=${URLEncoder.encode("37.467696")}&dest_lng=${URLEncoder.encode("127.101063")}","com.kakao.taxi")
//            openSearchApps("kakaot://taxi?${URLEncoder.encode("세곡동 557")}","com.kakao.taxi")
//            openSearchApps("kakaot://taxi?dest_addr=${URLEncoder.encode("세곡동 557")}","com.kakao.taxi")
        }
        setLayout()

        return binding.root
    }

    fun sendMsg(scheme : String? = null , pkg : String? = null) {
        var postIntent : Intent? = null
        if (scheme != null && scheme.length > 1) {
            postIntent = Intent(Intent.ACTION_VIEW,Uri.parse(scheme))
        } else {
            postIntent = Intent(Intent.ACTION_SEND)
            postIntent.type = "text/plain"
            postIntent.putExtra(Intent.EXTRA_TEXT, "${getInputText()}")
        }
        if (pkg != null && pkg.length > 1) {
            postIntent?.setPackage(pkg)
            startActivity(postIntent)
        } else {
            val chooserTitle = "바로 보냄"
            startActivity(Intent.createChooser(postIntent, chooserTitle))
        }
    }

    val appNames = hashSetOf<AppInfo>()
    val contactList = arrayListOf<SimpleContact>()

    fun openSearchApps(schemeString : String, pakage : String? = null) {
        val gmmIntentUri = Uri.parse(schemeString)
        val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
        pakage?.let {
            mapIntent.setPackage(pakage)
            WorkersDb.updateAppUse(pakage)
        }
        startActivity(mapIntent)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.searchInput.setOnKeyListener { v, keyCode, event ->
            //contactList.size < 1 && packageList.size < 1 &&
            if (keyCode == 66 &&  event.action == KeyEvent.ACTION_UP) {
                checkResult(binding.searchInput.text.toString())
                true
            }else {
                false
            }
        }
        binding.searchInput.doOnTextChanged{ inputText, _, _, _ ->
            binding.searchInput.text?.let { binding.searchInput.setSelection(it.length) }
            filterAppsList(inputText.toString())
        }
    }

    fun checkResult(keyword: String) {

//        if(!isAdded  || !isResumed || keyword.length < 1) return
//        var dialog : AlertDialog.Builder? = null
//        var filted = packageList.filter { it.appName.equals(keyword) }
//        BLog.LOGE("filted >> ${filted.size}")
//        var filtedContact = contactList.filter { it.name.equals(keyword) }
//        BLog.LOGE("filtedContact >> ${filtedContact.size}")
//        if (keyword.length > 0 && (packageList.size == 1 || filted.size > 0)) {
//            dialog = AlertDialog.Builder(requireContext())
//            dialog?.setTitle("앱 실행 확인")
//            if (packageList.size == 1) {
//                dialog?.setMessage("${keyword} 검색 결과 '${packageList[0].appName}' 준비됨")
//                dialog?.setPositiveButton("실행") { s, d ->
//                    runonUi {
//                        startActivity(packageManager?.getLaunchIntentForPackage(packageList[0].pkgName!!))
//                        s.dismiss()
//                    }
//                }
//            } else if (filted.size > 0) {
//                dialog?.setMessage("${keyword} 검색 결과 '${filted[0].appName}' 준비됨")
//                dialog?.setPositiveButton("${filted[0].appName} 실행") { s, d ->
//                    runonUi {
//                        startActivity(packageManager?.getLaunchIntentForPackage(filted[0].pkgName!!))
//                        s.dismiss()
//                    }
//                }
//                if(filted.size > 1) {
//                    dialog?.setNeutralButton("${filted[1].appName} 실행") { s, d ->
//                        runonUi {
//                            startActivity(packageManager?.getLaunchIntentForPackage(filted[1].pkgName!!))
//                            s.dismiss()
//                        }
//                    }
//                }
//            }
//            dialog?.setCancelable(false)
//            dialog?.setNegativeButton("취소") { s, d ->
//                runonUi { s.dismiss() }
//            }
//            dialog?.setOnDismissListener { registCancelSearch() }
//            dialog?.show()
//        } else if (contactList.size == 1 || filtedContact.size > 0) {
//            dialog = AlertDialog.Builder(requireContext())
//            dialog?.setTitle("연락처 실행 확인")
//            dialog?.setCancelable(false)
//            dialog?.setNegativeButton("취소") { s, d ->
//                runonUi { s.dismiss() }
//            }
//            if (contactList.size == 1) {
//                dialog?.setMessage("${keyword} 검색 결과 '${contactList[0].name}' 준비됨")
//                dialog?.setPositiveButton("자세히 보기") { s, d ->
//                    runonUi {
//                        ContactMenu().show(childFragmentManager, contactList[0].id.toString())
//                        s.dismiss()
//                    }
//                }
//            } else if(filtedContact.size > 0) {
//                dialog?.setMessage("${keyword} 검색 결과 '${filtedContact[0].name}' 준비됨")
//                dialog?.setPositiveButton("'${filtedContact[0].name},\n${filtedContact[0].phoneNumber}'\n자세히 보기") { s, d ->
//                    runonUi {
//                        ContactMenu().show(childFragmentManager, filtedContact[0].id.toString())
//                        s.dismiss()
//                    }
//                }
//                if (filtedContact.size > 1) {
//                    dialog?.setNeutralButton("'${filtedContact[1].name},\n${filtedContact[1].phoneNumber}'\n자세히 보기") { s, d ->
//                        runonUi {
//                            ContactMenu().show(childFragmentManager, filtedContact[1].id.toString())
//                            s.dismiss()
//                        }
//                    }
//                }
//            }
//            dialog?.setOnDismissListener { registCancelSearch() }
//            dialog?.show()
//        } else {
            lActivity?.openSearchMenus(keyword) {
                registCancelSearch()
            }
//        }
    }



    fun runonUi(invoke : () -> Unit) {
        Handler(Looper.getMainLooper()).run {
            try {
                invoke.invoke()
            }catch (e : Exception) {
                e.printStackTrace()
            }
        }
    }


    override fun onResume() {
        super.onResume()
        BLog.LOGE("onResume")
        fetchApps()

        binding.appsCount.visibility = if (settingsPrefs!!.getBoolean(KEY_APPS_COUNT, true)) VISIBLE else GONE

        openSearch()
        registCancelSearch()
        BLog.LOGE("onResume after chechHandler.postDelayed(cancelSearch, 3000L)")
    }

    val chechHandler = Handler(Looper.getMainLooper())

    val cancelSearch = Runnable { lActivity?.viewPager?.currentItem = 1 }

    fun registCancelSearch() {
        BLog.LOGE("Called registCancelSearch")
        chechHandler.removeCallbacks(cancelSearch)
        chechHandler.postDelayed(cancelSearch, 8000L)
    }

    fun clearCancelSearch() {
        chechHandler.removeCallbacks(cancelSearch)
    }

    override fun onPause() {
        super.onPause()
        closeSearch()
    }

    private fun setLayout() {
//        when (layoutType) {
//            0, 1 -> {
//                binding.appsList.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL,false)
//                appsAdapter!!.updateGravity(settingsPrefs!!.getInt(KEY_DRAW_ALIGN, Gravity.CENTER))
//            }
//            2 -> binding.appsList.layoutManager = GridLayoutManager(requireContext(), Math.min(settingsPrefs!!.getInt(KEY_GRID_COLUMNS, DEFAULT_GRID_COLUMNS), 4), GridLayoutManager.HORIZONTAL,false)
//        }
        binding.appsList.layoutManager = GridLayoutManager(requireContext(), 2, GridLayoutManager.HORIZONTAL,false)
        binding.contactList.layoutManager = GridLayoutManager(requireContext(), 2, GridLayoutManager.HORIZONTAL,false)
        /* initialize apps list adapter */
        binding.appsList.adapter = appsAdapter
        binding.contactList.adapter = contactAdapter
    }
    var appQuery : RealmResults<AppInfo>? = null
    fun fetchApps(keyword : String? = null) {
        WorkersDb.getRealm().apply {
            var newQ = query<AppInfo>()
            if (keyword != null && keyword.length > 0) {
                if (JamoUtils.CHOSUNG.contains(keyword.split("")[0])) {
                    newQ = newQ.query("appName CONTAINS $0 OR appNameChosung CONTAINS $0 OR koreanName CONTAINS $0 OR alphaCho CONTAINS $0 OR category CONTAINS $0", keyword)
                } else if(Pattern.matches("^[가-힣]*\$", keyword)){
                    newQ = newQ.query("appName CONTAINS $0 OR  koreanName CONTAINS $0 OR  category CONTAINS $0", keyword)
                }else {
                    keyword.split("").forEach {
                        if (it.length > 0) {
                            newQ = newQ.query(
                                "appName CONTAINS $0 OR category CONTAINS $0 OR pkgName CONTAINS $0 OR appName CONTAINS $1 OR category CONTAINS $1 OR pkgName CONTAINS $1",
                                keyword.lowercase(),
                                keyword.uppercase()
                            )
                        }
                    }
                }
            }
            appQuery = newQ.sort(Pair("clickCount", Sort.DESCENDING),Pair("lastUseDate",Sort.DESCENDING)).limit(20).find()
            appQuery?.let {
                if(it.size > 0) {
                    WorkersDb.getRealm().apply {
                        packageList.clear()
                        packageList.addAll(copyFromRealm(it))
                        BLog.LOGE("packageList >>> ${packageList.size}")
                        binding.appsList.post { if (packageList.size > 0) {
                            appsAdapter?.updateData(packageList)
                        } }
//                        val clo = packageList.clone()
//                        appNames.clear()
//                        appNames.addAll(packageList.filter { it.koreanName?.trim()?.length ?: 0 < 1 })
//                        getHangule()
                    }
                }
            }
        }
        fetcContact(keyword)
    }


    var contactQuery : RealmResults<SimpleContact>? = null
    fun fetcContact(keyword : String? = null) {
        WorkersDb.getRealm().apply {
            var newQ = query<SimpleContact>()
            if (keyword != null && keyword.length > 0) {
                if(Pattern.matches("^[0-9]*\$", keyword)){
                    keyword.split("").forEach {
                        if (it.length > 0) newQ = newQ.query("phoneNumber CONTAINS $0", keyword)
                    }
                } else {
                    newQ = newQ.query(
                        "name CONTAINS $0 OR  chosung CONTAINS $0",
                        keyword
                    )
                }
            }

            contactQuery = newQ.sort(Pair("touchCount", Sort.DESCENDING),Pair("lastedTouchDateTime",Sort.DESCENDING)).find()
            contactQuery?.let {
                if (it.size > 0)
                    WorkersDb.getRealm().apply {
                        contactList.clear()
                        contactList.addAll(copyFromRealm(it).toList())
                        BLog.LOGE("packageList >>> ${contactList.size}")
                        binding.contactList.post { if (contactList.size > 0) {
                            contactAdapter?.updateData(contactList)
                        } }
                    }
            }

        }
    }

    fun getHangule() {
        BLog.LOGE("on getHangule")
        Executors.newSingleThreadScheduledExecutor().schedule({
            if (appNames.size > 0) {
                val info = appNames.first()
                appNames.remove(info)
                if (info.koreanName?.length ?: 0 > 0 || info.appNameChosung?.length ?: 0 > 0) {
                    getHangule()
                } else {
                    BLog.LOGE("on getHangule ${info.appName}")
                    if (Pattern.matches("^[a-zA-Z]*$", info.appName)) {
//                        Jsoup.connect("https://translate.google.com/?hl=ko&sl=en&tl=ko&text=${info.appName}&op=translate").get().let { trans ->
//                            BLog.LOGE("on getHangule ${trans.title()}")
//                            trans.getElementsByTag("span").forEach {
//                                BLog.LOGE("on getHangule ${it.text()}")
//                                if(it.hasAttr("jsaction") &&
//                                    it.attr("jsaction").contains("mouseout") &&
//                                    it.attr("jsaction").contains("contextmenu") &&
//                                    it.attr("jsaction").contains("mouseover")
//                                    ) {
//                                    BLog.LOGE("on getHangule $it")
//                                }
//                            }
//
//                        }.apply {
//                            getHangule()
//                        }
                        Handler(Looper.getMainLooper()).post {
                            LauncherActivity.Companion.lActivity?.doWebParseStart(
                                "https://translate.google.com/?hl=ko&sl=en&tl=ko&text=${info.appName}&op=translate",
                                object : CommadCallabck {
                                    override fun onConsoleLog(log: String) {
                                        if (log.contains("result::")) {
                                            val appHangulName = log.split("result::")[1]
                                            if(appHangulName?.length ?: 0 > 0) {
                                                info.appNameChosung = JamoUtils.split(appHangulName).joinToString("")
                                                info.koreanName = appHangulName
                                                BLog.LOGE("appHangulName >>> $appHangulName")
                                                BLog.LOGE("appHangulName >>> ${info.appNameChosung}")
                                                WorkersDb.update(info)
                                                getHangule()
                                            }
                                        }
                                    }

                                    override fun collectComplete() {
                                        getHangule()
                                    }
                                })
                        }
                    } else {
                        info.appNameChosung = JamoUtils.split(info.appName).joinToString("")
                        info.koreanName = info.appName
                        WorkersDb.update(info)
                        getHangule()
                        BLog.LOGE("on getHangule to next")
                    }
                }
            }
        },5,TimeUnit.SECONDS)
    }

    private fun getAlphabetItems() {
//        settingsPrefs!!.getInt(KEY_SCROLLBAR_HEIGHT, DEFAULT_SCROLLBAR_HEIGHT).let { height: Int ->
//            if (height == 0) { binding.alphabets.visibility = GONE }
//            else {
//                binding.alphabets.apply {
//                    if (visibility == GONE) visibility = VISIBLE
//                    updateLayoutParams { this.height = height }
//                }
//                alphabetList.clear()
//                for (mPackage in packageList) {
//                    mPackage.appName.first().uppercase().let { firstLetter: String ->
//                        when {
//                            numberPattern.matcher(firstLetter).matches() -> alphabetList.add(0, "#")
//                            alphabetPattern.matcher(firstLetter).matches() -> alphabetList.add(firstLetter)
//                            !numberPattern.matcher(firstLetter).matches() &&
//                                    !alphabetPattern.matcher(firstLetter).matches() -> alphabetList.add(alphabetList.size,"⠶")
//                            else -> {}
//                        }
//                    }
//                }
//                binding.alphabets.invalidate()
//            }
//        }
    }

    var lastSearchStringLength = 0
    var lastSearchString : String = ""
    private fun filterAppsList(searchString: String) {
        /* check each app name and add if it matches the search string */
        fetchApps(searchString)
//        if (searchString.length > 0 && (lastSearchStringLength != searchString.length || lastSearchString.equals(searchString) == false)) {
//            BLog.LOGE("START FILTER")
//            packageList.clear()
//            for (pkg in oringinPackageList) {
//                if (pkg.appName!!.contains(searchString,true) || pkg.category!!.contains(searchString,true) || pkg.pkgName!!.contains(searchString,true)) {
//                    BLog.LOGE("pkg >>> ${pkg.category}  , ${pkg.appName}")
//                    packageList.add(pkg)
//                }
//            }
//            packageList.sortBy { it.appName }
//            BLog.LOGE("MIDDLE FILTER")
//
//            appsAdapter?.updateData(packageList)
//
//            contactList.clear()
//            for (item in originContactList) {
//                if (item.name!!.contains(searchString) || item.phoneNumber!!.contains(searchString)) {
//                    contactList.add(item)
//                }
//            }
//            contactList.sortBy { it.name }
//            contactAdapter?.updateData(contactList)
//            BLog.LOGE("END FILTER")
//
//
//        } else if(lastSearchStringLength == 0){
//            contactList.clear()
//            for (item in originContactList) {
//                contactList.add(item)
//            }
//            packageList.clear()
//            for (resolver in oringinPackageList) {
//                packageList.add(resolver)
//            }
//            appsAdapter?.updateData(packageList)
//            contactAdapter?.updateData(contactList)
//        } else {
//            afterClearSearch()
//
//        }
        lastSearchString = searchString
        lastSearchStringLength = searchString.length
        registCancelSearch()
    }

    private fun openSearch() {
        binding.searchInput.apply {
            visibility = VISIBLE
            requestFocus()
            let {
                (lActivity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.showSoftInput(it, InputMethodManager.SHOW_IMPLICIT)
            }
        }
    }

    /* clear search string, hide keyboard and search box */
    private fun closeSearch() {
        binding.searchInput.apply {
            let {
                text?.clear()
                (lActivity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(it.windowToken, 0)
            }
        }
    }

    private fun setKeyboardPadding() {
//        binding.root.viewTreeObserver.addOnGlobalLayoutListener {
//            val rect = Rect()
//            binding.root.getWindowVisibleDisplayFrame(rect)
//            val screenHeight = binding.root.height
//            val keyboardHeight = screenHeight - (rect.bottom - rect.top)
//
//            when {
//                keyboardHeight > screenHeight * 0.15 -> {
//                    if (!isKeyboardShowing &&
//                        !settingsPrefs!!.getBoolean(KEY_STATUS_BAR, false)) {
//                        isKeyboardShowing = true
//                        binding.root.setPadding(0, 0, 0, keyboardHeight)
//                    }
//                }
//                else -> {
//                    if (isKeyboardShowing) {
//                        isKeyboardShowing = false
//                        binding.root.setPadding(0, 0, 0, 0)
//                    }
//                }
//            }
//        }
    }

}

fun normalize(str: String): String {
    val normalizedString =
        Normalizer.normalize(str.replace("\\W".toRegex(), ""), Normalizer.Form.NFC)
    val pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+")
    return pattern.matcher(normalizedString).replaceAll("").toLowerCase()
}