package com.test.basd.smartjunkcleaner.activity.browser

import android.app.Activity
import android.graphics.Bitmap
import android.os.Build
import android.webkit.CookieManager
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.blankj.utilcode.util.SPUtils

class BrowserView(listener: WebViewListener, val str: String) {
    companion object {
        private const val DESKTOP_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36"
        private var mDefaultUserAgent = ""
    }

    private val mWebView = WebView(listener.activity)
    private val settings = mWebView.settings

    var icon: Bitmap? = null
    var title = str
    var progress = 0
    var url = str
    var isHome = false

    init {
        mWebView.drawingCacheBackgroundColor = -1
        mWebView.isFocusableInTouchMode = true
        mWebView.isFocusable = true
        mWebView.isDrawingCacheEnabled = false
        mWebView.setWillNotCacheDrawing(true)
        if (Build.VERSION.SDK_INT <= 22) {
            mWebView.isAnimationCacheEnabled = false
            mWebView.isAlwaysDrawnWithCacheEnabled = false
        }
        mWebView.setBackgroundColor(-1)
        mWebView.isScrollbarFadingEnabled = true
        mWebView.isSaveEnabled = true
        mWebView.setNetworkAvailable(true)
        mWebView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                progress = newProgress
                listener.onProgressChanged(newProgress)
            }

            override fun onReceivedTitle(view: WebView?, title: String?) {
                this@BrowserView.title = title?.takeIf { it.isNotBlank() } ?: str
                listener.onReceivedTitle(title ?: str)
            }

            override fun onReceivedIcon(view: WebView?, icon: Bitmap?) {
                this@BrowserView.icon = icon
                listener.onReceivedIcon(icon)
            }
        }
        mWebView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                this@BrowserView.url = url ?: ""
                listener.onPageFinished(view, url ?: "")
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                this@BrowserView.url = url ?: ""
                listener.onPageStarted(url ?: "", favicon)
            }
        }
        settings.setGeolocationEnabled(false)
        settings.userAgentString = WebSettings.getDefaultUserAgent(listener.activity)
        settings.saveFormData = false
        settings.javaScriptEnabled = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
        try {
            settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING
        } catch (_: Exception) {}
        settings.loadsImagesAutomatically = true
        settings.setSupportMultipleWindows(true)
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.textZoom = 100
        mDefaultUserAgent = settings.userAgentString
        CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true)

        if (SPUtils.getInstance().getBoolean("desktop_mode", false)) {
            setDesktop()
        } else {
            setPhone()
        }

        if (str.trim().isNotEmpty()) {
            mWebView.loadUrl(str)
        }
    }

    fun loadUrl(url: String) {
        mWebView.loadUrl(url)
    }

    fun setDesktop() {
        settings.userAgentString = DESKTOP_USER_AGENT
    }

    fun setPhone() {
        settings.userAgentString = mDefaultUserAgent
    }

    fun reload() {
        mWebView.reload()
    }

    fun canGoBack() = mWebView.canGoBack()

    fun goBack() = mWebView.goBack()

    fun canGoForward() = mWebView.canGoForward()

    fun goForward() = mWebView.goForward()

    fun getWebView() = mWebView

    interface WebViewListener {
        val activity: Activity

        fun onProgressChanged(progress: Int)

        fun onReceivedTitle(title: String)

        fun onReceivedIcon(icon: Bitmap?)

        fun onPageStarted(url: String, icon: Bitmap?)

        fun onPageFinished(view: WebView?, url: String)
    }
}