package com.mime.dualscreenview.webcontents

import android.app.AlertDialog
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.util.Log
import android.webkit.*
import androidx.core.net.toUri
import com.mime.dualscreenview.common.Blog
import com.mime.dualscreenview.common.PrefManager
import com.mime.dualscreenview.data.HistoryManager
import com.mime.dualscreenview.data.model.LastInfo
import com.mime.dualscreenview.webcontents.contentsinfo.Booktoki
import com.mime.dualscreenview.webcontents.contentsinfo.DidFindContents
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONObject


open class BaseWebContentsViewer {

    var currentContentsProvider : BaseWebContents? = null
    lateinit var webview : WebView
    lateinit var mainControllInterface : MainControllInterface

    @JavascriptInterface
    fun onBookInfo(jsonData : String) {
        GlobalScope.launch {
            try {
                Blog.LOGE("BaseWebContentsViewer",jsonData)
                val data: JSONObject = JSONObject(jsonData)
                Blog.LOGE("BaseWebContentsViewer",data.toString())
                mainControllInterface?.onBookInfos(jsonData)
            } catch (e : Exception) {

            }
        }
    }

    constructor(webview : WebView, mainControllInterface : MainControllInterface ) {
        this.webview = webview
        this.mainControllInterface = mainControllInterface
        webview.webChromeClient = rootWebChromeClient
        webview.webViewClient = rootWebViewClient
        webview.settings.textZoom = 100
        webview.addJavascriptInterface(this,"PAgit")
        webview.settings.javaScriptEnabled = true
        webview.settings.javaScriptCanOpenWindowsAutomatically = false
        webview.settings.loadWithOverviewMode = true
        webview.settings.setPluginState(WebSettings.PluginState.ON)
        webview.settings.domStorageEnabled = true
        webview.clearCache(true);
        webview.clearHistory();
        webview.clearSslPreferences();
        WebView.setWebContentsDebuggingEnabled(true)
    }

    constructor()

    fun loadContents(webContents: BaseWebContents) {
        currentContentsProvider = webContents
        currentContentsProvider?.let {
            webview.loadUrl(it.getLastedDoamin())
        }

    }

    val rootWebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
        }
    }

    fun findListItem(callBakItems : DidFindContents) {
        currentContentsProvider?.findListItem(webview,callBakItems)
    }

    fun loadLastInfo(lastInfo: LastInfo) {
        lastInfo?.let { last ->
            currentContentsProvider = WebContentsManger.getBaseWebContentsBy(last.contentsName)
            if (last.pageUrl.startsWith("https://")) {
                webview.loadUrl(last.pageUrl)
            } else {
                try {
                    webview.loadUrl(PrefManager.getLastDomain().plus("/").plus(last.pageUrl))
                } catch (e : Exception) {
                    webview.loadUrl(PrefManager.getLastDomain())
                }
            }
        }
    }

    val rootWebViewClient = object : WebViewClient() {

        override fun shouldInterceptRequest(
            view: WebView?,
            request: WebResourceRequest?
        ): WebResourceResponse? {
            Log.e("shouldInterceptRequest", " >>>> ${request?.url?.toString()} ,  ${request?.url?.toString()?.contains("gif")}")

            if(request?.url?.toString()?.contains("gif") ?: false) {
                return WebResourceResponse("text/javascript", "UTF-8", null);
            }
//            if(request?.url?.toString()?.contains(currentContentsProvider?.acccceptResourceKeyword() ?: "") == false && request?.url?.toString()?.contains(currentContentsProvider?.getLastedDoamin() ?: "") == false) {
//                return WebResourceResponse("text/javascript", "UTF-8", null);
//            }
            return super.shouldInterceptRequest(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            mainControllInterface?.onStartLoad()
        }

        override fun onReceivedSslError(
            view: WebView?,
            handler: SslErrorHandler?,
            error: SslError?
        ) {
//            super.onReceivedSslError(view, handler, error)
            Blog.LOGE(log= "onReceivedSslError >> ${error}")
            handler?.proceed()
        }
        override fun onReceivedHttpError(
            view: WebView?,
            request: WebResourceRequest?,
            errorResponse: WebResourceResponse?
        ) {
            Blog.LOGE(log= "onReceivedHttpError >> ${errorResponse}")
//            super.onReceivedHttpError(view, request, errorResponse)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            view?.let {
                url?.toUri()?.let {
                    PrefManager.putLastDomain(it.scheme.plus("::/").plus(it.host))
                }

                if(url?.contains("/list/") ?: false && url?.contains("agit") ?: false){
                    findListItem {
                        Blog.LOGE("onPageFinished", url ?: "")
                    }
                } else if (url?.contains("booktoki") ?: false){
                    findListItem {
                        Blog.LOGE("onPageFinished", url ?: "")
                    }
                }
                
                currentContentsProvider?.doOnloaded(it , { result ->
                    result?.let { mainControllInterface.onLoadedContents(it) }
                } , { complete ->
                    if(complete) {
                        mainControllInterface?.completePageLoad(LastInfo().apply {
                            this.pageUrl = url?.toUri()?.path ?: currentContentsProvider?.getLastedDoamin() ?: ""
                            this.contentsName = currentContentsProvider?.getWebcontentsName() ?: ""
                            this.pageIndex = 0
                        })
                    }
                })
            }
        }
    }
}