package com.base.browserwhite.ui.activity.webbrowser


import android.graphics.Color
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.base.browserwhite.R
import com.base.browserwhite.ads.AdmobMaxHelper
import com.base.browserwhite.ads.AdmobMaxHelper.lastShowInter
import com.base.browserwhite.bean.ConstObject
import com.base.browserwhite.bean.ConstObject.GOOGLE
import com.base.browserwhite.databinding.ActivityWebBrowserBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.views.DialogViews.showSearchEngineDialog
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.LinkSearchUtils.getBaiduSearch
import com.base.browserwhite.utils.LinkSearchUtils.getBingSearch
import com.base.browserwhite.utils.LinkSearchUtils.getDuckDuckGoSearch
import com.base.browserwhite.utils.LinkSearchUtils.getGoogleSearch
import com.base.browserwhite.utils.LinkSearchUtils.getSearchUrl
import com.base.browserwhite.utils.LinkSearchUtils.getYahooSearch
import com.base.browserwhite.utils.LinkSearchUtils.getYandexSearch
import com.base.browserwhite.utils.LinkSearchUtils.handleInput


class WebBrowserActivity : BaseActivity<ActivityWebBrowserBinding>() {

    override val binding: ActivityWebBrowserBinding by lazy {
        ActivityWebBrowserBinding.inflate(layoutInflater)
    }
    private val fragmentList = arrayListOf<Fragment>()
    private var currentFragment: WebViewFragment? = null
    private var searchAction: (context: String) -> String = ::getBaiduSearch

    var from: String = ""

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        from = intent.extras?.getString("from") ?: ""
        val url = intent.extras?.getString("url") ?: ""
        binding.editWeb.setText(url)

        val searchEngine = intent.extras?.getString("searchEngine") ?: GOOGLE
        when (searchEngine) {
            GOOGLE -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_google)
                searchAction = ::getGoogleSearch
            }

            ConstObject.BING -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_bing)
                searchAction = ::getBingSearch
            }

            ConstObject.YAHOO -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yahoo)
                searchAction = ::getYahooSearch
            }

            ConstObject.DUCKDUCKGO -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_xuckd)
                searchAction = ::getDuckDuckGoSearch
            }

            ConstObject.YANDEX -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yandex)
                searchAction = ::getYandexSearch
            }

            ConstObject.BAIDU -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_baidu)
                searchAction = ::getBaiduSearch
            }

        }

        addNewWebSite(url)

    }


    private fun checkLeftRight() {
        if (currentFragment?.canGoBack() == true) {
            binding.ivLeft.setImageResource(R.mipmap.left_s)
        } else {
//            binding.ivLeft.setImageResource(R.mipmap.left_n)
            binding.ivLeft.setImageResource(R.mipmap.left_s)
        }
        if (currentFragment?.canGoForward() == true) {
            binding.ivRight.setImageResource(R.mipmap.right_s)
        } else {
            binding.ivRight.setImageResource(R.mipmap.right_n)
        }
        binding.editWeb.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    val input = v?.text?.toString()
                    if (input.isNullOrEmpty()) {
                        return true
                    }
                    handleInput(input,
                        loadUrl = { url ->
                            currentFragment?.loadWebView(url)
                        },
                        performSearch = { search ->
                            currentFragment?.loadWebView(getSearchUrl(search))
                        })

                    return true // 返回true表示事件已处理
                }
                return false

            }
        })
    }

    override fun initListener() {
        super.initListener()

        onBackPressedDispatcher.addCallback {

            if (currentFragment?.canGoBack() == true) {
                currentFragment?.goBack()
            } else {
                when (from) {

                    "WevStoreActivity" -> {

                        if (System.currentTimeMillis() - lastShowInter > 10 * 1000 * 1000 || lastShowInter == 0L) {
                            AdmobMaxHelper.admobMaxShowInterstitialAd(this@WebBrowserActivity, false) {
                                lastShowInter = System.currentTimeMillis()
                                finishToMain()
                            }
                        }


                    }

                    else -> finishToMain()
                }

            }
        }
        binding.ivLeft.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.ivRight.setOnClickListener {
            if (currentFragment?.canGoForward() == true) {
                currentFragment?.goForward()
            }
        }
        binding.ivHome.setOnClickListener {
            finishToMain()
        }
        binding.flSearchEngine.setOnClickListener {
            showSearchEngineDialog { website ->
                when (website) {
                    ConstObject.GOOGLE -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_google)
                        searchAction = ::getGoogleSearch
                    }

                    ConstObject.BING -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_bing)
                        searchAction = ::getBingSearch
                    }

                    ConstObject.YAHOO -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yahoo)
                        searchAction = ::getYahooSearch
                    }

                    ConstObject.DUCKDUCKGO -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_xuckd)
                        searchAction = ::getDuckDuckGoSearch
                    }

                    ConstObject.YANDEX -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yandex)
                        searchAction = ::getYandexSearch
                    }

                    ConstObject.BAIDU -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_baidu)
                        searchAction = ::getBaiduSearch
                    }

                }
            }
        }

    }

    private fun addNewWebSite(uri: String) {
        val myFragment = WebViewFragment().apply { url = uri }
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.container, myFragment)
        transaction.commit()
        fragmentList.add(myFragment)
        currentFragment = myFragment
        currentFragment?.onPageFinished = { uriString ->
            uriString?.let { binding.editWeb.setText(it) }
            checkLeftRight()
        }
    }

}