package com.example.base.browser

import android.content.Context
import android.content.Intent
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Bundle
import android.view.ViewGroup
import android.view.WindowManager
import android.webkit.WebResourceRequest
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.base.R
import com.example.base.utils.DensityUtils
import com.example.base.widget.TitleBar
import com.gyf.immersionbar.ImmersionBar
import com.just.agentweb.AbsAgentWebSettings
import com.just.agentweb.AgentWeb
import com.just.agentweb.MiddlewareWebChromeBase
import com.just.agentweb.MiddlewareWebClientBase

/**
 * 全局浏览器Activity
 * 使用了agentWeb {@link https://github.com/Justson/AgentWeb }
 */
class BrowserActivity : AppCompatActivity() {

    private val titleStr by lazy { intent.getStringExtra(ARG_TITLE) }
    private val url by lazy { intent.getStringExtra(ARG_URL) }

    private val zoom by lazy { intent.getBooleanExtra(ARG_ZOOM, false) }


    private lateinit var mAgentWeb: AgentWeb
    private lateinit var mPreAgentWeb: AgentWeb.PreAgentWeb


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.mvvm_activity_browser)
        if (immersionBarEnabled()) {
            initImmersionBar()
        }
        initView()
    }

    private fun initImmersionBar() {
        ImmersionBar.with(this)
            .keyboardEnable(false)
            .statusBarColor(android.R.color.transparent)
            .navigationBarColor(android.R.color.black)
            .statusBarDarkFont(true)
            .navigationBarDarkIcon(true)
            .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
            .init()
    }

    private fun immersionBarEnabled(): Boolean {
        return true
    }

    private fun initView() {
        setSupportActionBar(findViewById(R.id.mTitleBar))
        supportActionBar?.setHomeAsUpIndicator(R.drawable.mvvm_ic_close_black)
        title = titleStr

        mPreAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(findViewById(R.id.content), ViewGroup.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .useMiddlewareWebChrome(mMiddlewareWebChromeBase)
            .useMiddlewareWebClient(mMiddlewareWebClientBase)
            .setAgentWebWebSettings(CustomSettings())
            .createAgentWeb()
            .ready()

        mAgentWeb = mPreAgentWeb.go(url)

        setBackColor(android.R.color.black)

        ImmersionBar.setTitleBar(this, findViewById(R.id.mTitleBar))
        ImmersionBar.setStatusBarView(this, DensityUtils.getStatusBarHeight(this))
        ImmersionBar.with(this).statusBarDarkFont(false).init()
    }

    fun setBackColor(color: Int) {
        val upArrow = ContextCompat.getDrawable(this, R.drawable.ic_back)
        upArrow?.colorFilter = PorterDuffColorFilter(ContextCompat.getColor(this, color), PorterDuff.Mode.SRC_ATOP)
        supportActionBar?.setHomeAsUpIndicator(upArrow)
    }

    private val mMiddlewareWebChromeBase = object : MiddlewareWebChromeBase() {
        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
//            this@BrowserActivity.title = title
        }
    }

    private val mMiddlewareWebClientBase = object : MiddlewareWebClientBase() {

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            val uri = request?.url
            return if (uri?.scheme?.contains("http") == true) {
                super.shouldOverrideUrlLoading(view, request)
            } else {
                view?.stopLoading()
                try {
                    startActivity(Intent(Intent.ACTION_VIEW, uri))
                } catch (e: Exception) {
                }
                false
            }
        }

    }

    /**
     * 重置标题
     */
    override fun onTitleChanged(title: CharSequence?, color: Int) {
        super.onTitleChanged(title, color)
        val titleBar = findViewById<TitleBar>(R.id.mTitleBar)
        titleBar?.title = title
    }


    /**
     * 设置toolbar的返回键 调用onBackPressed
     */
    override fun onSupportNavigateUp(): Boolean {
        finish()
        return true
    }

    /**
     * 返回键
     */
    override fun onBackPressed() {
        if (!mAgentWeb.back()) {
            super.onBackPressed()
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent?.extras != null) {
            title = intent.extras!!.getString(ARG_TITLE)
            val url = intent.extras!!.getString(ARG_URL)
            mPreAgentWeb.go(url)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mAgentWeb.destroy()
    }


    companion object {
        const val ARG_TITLE = "arg_title"
        const val ARG_URL = "arg_url"
        const val ARG_ZOOM = "arg_zoom"

        /**
         * @param title
         * @param url
         * @param zoom
         */
        fun start(context: Context?, title: String?, url: String?, zoom: Boolean = false) {
            val intent = Intent(context, BrowserActivity::class.java)
            intent.putExtra(ARG_TITLE, title)
            intent.putExtra(ARG_URL, url)
            intent.putExtra(ARG_ZOOM, zoom)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context?.startActivity(intent)
        }
    }

    inner class CustomSettings : AbsAgentWebSettings() {

        override fun toSetting(webView: WebView?): AbsAgentWebSettings {
            super.toSetting(webView)
            if (zoom) {
                webSettings.builtInZoomControls = true
                webSettings.displayZoomControls = false
                webSettings.useWideViewPort = true
                webSettings.loadWithOverviewMode = true
            }
            return this
        }

        override fun bindAgentWebSupport(agentWeb: AgentWeb?) {
            this.mAgentWeb = agentWeb
        }
    }
}
