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


import android.content.Intent
import android.graphics.Color
import android.view.KeyEvent
import android.view.View
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 androidx.lifecycle.lifecycleScope
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.bean.ConstObject.searchEngineSp
import com.base.browserwhite.databinding.ActivityWebBrowserBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.activity.bookmark.BookmarkActivity
import com.base.browserwhite.ui.activity.bookmark.BookmarkEditActivity
import com.base.browserwhite.ui.activity.search.SearchActivity
import com.base.browserwhite.ui.views.DialogViews.showAddRootBookmarkDialog
import com.base.browserwhite.ui.views.DialogViews.showSearchEngineDialog
import com.base.browserwhite.ui.views.DialogViews.showWebBrowserMoreDialog
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.getSpSearchAction
import com.base.browserwhite.utils.LinkSearchUtils.getYahooSearch
import com.base.browserwhite.utils.LinkSearchUtils.getYandexSearch
import com.base.browserwhite.utils.LinkSearchUtils.handleInput
import com.base.browserwhite.utils.SpBeanUtils
import com.base.browserwhite.utils.SpBeanUtils.BOOKMARK_SP_KEY
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


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 = ::getSpSearchAction

    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") ?: searchEngineSp
        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)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        binding.ivShare.visibility = View.VISIBLE
    }


    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) {
                                if (it) {
                                    lastShowInter = System.currentTimeMillis()
                                }
                                finishToMain()
                            }
                        } else {
                            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 ->
                searchEngineSp = website
                searchAction = ::getSpSearchAction
                when (website) {
                    ConstObject.GOOGLE -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_google)
                    }

                    ConstObject.BING -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_bing)
                    }

                    ConstObject.YAHOO -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yahoo)
                    }

                    ConstObject.DUCKDUCKGO -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_xuckd)
                    }

                    ConstObject.YANDEX -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yandex)
                    }

                    ConstObject.BAIDU -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_baidu)
                    }

                }
            }
        }
        binding.ivMore.setOnClickListener {
            showWebBrowserMoreDialog(
                bookmarkAction = {
                    startActivity(Intent(this, BookmarkActivity::class.java))
                },
                joinAction = {
                    currentFragment?.bookmarkBean?.let { SpBeanUtils.addSpBean(BOOKMARK_SP_KEY, it) }
                    val dialog = showAddRootBookmarkDialog {
                        BookmarkEditActivity.editBookmark = currentFragment?.bookmarkBean
                        startActivity(Intent(this, BookmarkEditActivity::class.java))
                    }
                    lifecycleScope.launch {
                        delay(2500)
                        dialog.dismiss()
                    }
                })
        }

        binding.ivShare.setOnClickListener {
            val shareIntent = Intent()
            shareIntent.setAction(Intent.ACTION_SEND)
            shareIntent.putExtra(Intent.EXTRA_TEXT, currentFragment?.url)
            shareIntent.setType("text/plain")
        }
        binding.editWeb.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                binding.editWeb.selectAll()
                binding.ivShare.visibility = View.GONE
                SearchActivity.startActivityWithButtonExpandAnimation(this, binding.clSearch, 0)
                v.clearFocus()
            }
        }

    }
    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()
        }
    }

}