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


import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.activity.addCallback
import androidx.core.content.ContextCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import com.base.browserwhite.MyApplication
import com.base.browserwhite.R
import com.base.browserwhite.ads.AdmobMaxHelper
import com.base.browserwhite.ads.AdmobMaxHelper.lastShowInter
import com.base.browserwhite.bean.BookmarkBean
import com.base.browserwhite.bean.ConstObject
import com.base.browserwhite.bean.ConstObject.GOOGLE
import com.base.browserwhite.bean.ConstObject.searchEngineSp
import com.base.browserwhite.bean.ConstObject.webPrivacy
import com.base.browserwhite.databinding.ActivityWebBrowserBinding
import com.base.browserwhite.help.Constants
import com.base.browserwhite.help.RxBus
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.download.WebDownloadManagerActivity
import com.base.browserwhite.ui.activity.search.SearchActivity
import com.base.browserwhite.ui.views.DialogViews.showAddRootBookmarkDialog
import com.base.browserwhite.ui.views.DialogViews.showDeleteTipDialog
import com.base.browserwhite.ui.views.DialogViews.showMyAccountDialog
import com.base.browserwhite.ui.views.DialogViews.showSearchEngineDialog
import com.base.browserwhite.ui.views.DialogViews.showWebBrowserMoreDialog
import com.base.browserwhite.ui.views.ViewObject.setEditPrivacy
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.getSpSearchAction
import com.base.browserwhite.utils.LinkSearchUtils.getYahooSearch
import com.base.browserwhite.utils.LinkSearchUtils.getYandexSearch
import com.base.browserwhite.utils.SpBeanUtils
import com.base.browserwhite.utils.SpBeanUtils.BOOKMARK_SP_KEY
import com.base.browserwhite.utils.Utils
import com.base.browserwhite.utils.Utils.dpToPx
import com.google.gson.Gson
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
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
    private var mChangeSearchUrl: Observable<String>? = null

    var from: String = ""

    @SuppressLint("CheckResult")
    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
            }

        }

        mChangeSearchUrl = RxBus.get().register(Constants.CHANGE_SEARCH_URL, String::class.java)
        mChangeSearchUrl?.observeOn(AndroidSchedulers.mainThread())?.subscribe { t ->
            currentFragment?.loadWebView(t)
            binding.editWeb.setText(t)
        }

        addNewWebSite(url)
        val action = intent.getStringExtra("action") ?: ""
        if (TextUtils.equals(action, "search")) {
            binding.clSearch.post {
                resetSearchLayout()
            }
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 10087) {
            resetSearchLayout()
        }
    }

    private fun resetSearchLayout() {
        val screenWidth = Utils.getScreenWidth(MyApplication.context) - MyApplication.context.dpToPx(30f)
        val reverseScaleXAnimator =
            ObjectAnimator.ofFloat(binding.clSearch, "scaleX", screenWidth / binding.clSearch.width.toFloat(), 1f)
        val reverseScaleYAnimator = ObjectAnimator.ofFloat(binding.clSearch, "scaleY", 50f / 44f, 1f)
        binding.clSearch.pivotX = 0f
        binding.clSearch.pivotY = 0f
        reverseScaleXAnimator.setDuration(500)
        reverseScaleYAnimator.setDuration(500)
        val reverseAnimatorSet = AnimatorSet().apply {
            playTogether(reverseScaleXAnimator, reverseScaleYAnimator)
        }

        reverseAnimatorSet.start()

        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.flRefresh.setOnClickListener {
            currentFragment?.reloadWebView()
        }
    }

    override fun initListener() {
        super.initListener()

        onBackPressedDispatcher.addCallback {

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

                    "WevStoreActivity" -> {

                        if (System.currentTimeMillis() - lastShowInter > 40 * 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 {
            if (System.currentTimeMillis() - lastShowInter > 40 * 1000 * 1000 || lastShowInter == 0L) {
                AdmobMaxHelper.admobMaxShowInterstitialAd(this@WebBrowserActivity, false) {
                    if (it) {
                        lastShowInter = System.currentTimeMillis()
                    }
                    finishToMain()
                }
            } else {
                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.ivShare.setOnClickListener {
            val shareIntent = Intent()
            shareIntent.setAction(Intent.ACTION_SEND)
            shareIntent.putExtra(Intent.EXTRA_TEXT, currentFragment?.url)
            shareIntent.setType("text/plain")
            runCatching {
                startActivity(shareIntent)
            }
        }
        binding.editWeb.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                binding.editWeb.selectAll()
                binding.ivShare.visibility = View.INVISIBLE
                SearchActivity.searchContent = binding.editWeb.text.toString()

                SearchActivity.startActivityWithButtonExpandAnimation(this, binding.clSearch, 0)
                v.clearFocus()
            }
        }
        binding.ivMore.setOnClickListener {
            val json = getAddedBookmarkJson(currentFragment?.bookmarkBean?.url ?: "")

            showWebBrowserMoreDialog(
                bookmarkAdded = json != null,
                bookmarkAction = {
                    startActivity(Intent(this, BookmarkActivity::class.java))
                },
                joinAction = {
                    if (json == null) {
                        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()
                        }
                    } else {
                        val bean = Gson().fromJson(json, BookmarkBean::class.java)
                        showDeleteTipDialog("Delete Bookmark [${bean.name}]") {
                            SpBeanUtils.deleteSpBeanCondition(BOOKMARK_SP_KEY, bean.id)
                        }
                    }

                },
                refreshAction = {
                    currentFragment?.reloadWebView()
                },
                historyAction = {
                    startActivity(Intent(this, BookmarkActivity::class.java).apply {
                        putExtra("page", 1)
                    })
                },
                downloadAction = {
                    startActivity(Intent(this, WebDownloadManagerActivity::class.java).apply {
                        putExtra("update", true)
                    })
                },
                settingAction = {
                    showMyAccountDialog(launcher)
                },
                privacyAction = {
                    setEditPrivacy(this, binding.editWeb)
                }
            )
        }

    }

    override fun onResume() {
        super.onResume()
        setEditPrivacy(this, binding.editWeb)
    }

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

    override fun onDestroy() {
        super.onDestroy()
        mChangeSearchUrl?.let {
            RxBus.get().unregister(Constants.CHANGE_SEARCH_URL, it)
        }

    }

    private fun getAddedBookmarkJson(url: String): String? {
        return SpBeanUtils.getSpBeanList(BOOKMARK_SP_KEY).find { Gson().fromJson(it, BookmarkBean::class.java).url == url }
    }

}