package com.mime.dualscreenview.webcontents

import android.app.AlertDialog
import android.graphics.Bitmap
import android.net.http.SslError
import android.util.Log
import android.webkit.*
import com.mime.dualscreenview.common.Blog
import com.mime.dualscreenview.data.HistoryManager
import com.mime.dualscreenview.data.model.LastInfo
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)
//            HistoryManager.getBooPageInfo(last.pageUrl,{ page ->
//                if(page != null){
//                    if(page.contents?.length ?: 0 > 0) {
//                        mainControllInterface?.onLoadedContents(page.contents!!)
//                    } else {
//                        webview.loadUrl(last.pageUrl)
//                    }
//                } else {
                    webview.loadUrl(last.pageUrl)
//                }
//            })
        }
    }

    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()
        }
        var alertDialogs : ArrayList<AlertDialog> = arrayListOf()
//        override fun onReceivedError(
//            view: WebView?,
//            request: WebResourceRequest?,
//            error: WebResourceError?
//        ) {
//            super.onReceivedError(view, request, error)
//            if (error != null && error.errorCode < 0) {
//
//                webview.postDelayed({
//                    val builder = AlertDialog.Builder(webview.context)
//
//
//                    builder.setTitle("로딩 에러").setMessage("${currentContentsProvider?.getWebcontentsName()} ${currentContentsProvider?.lastNumber?.inc()} 여기로 다시 시도?!!")
//                    builder.setPositiveButton(
//                        "오키 ${currentContentsProvider?.lastNumber?.inc()} 레고!"
//                    ) { dialog, id ->
//                        dialog.dismiss()
//                        currentContentsProvider?.lastNumber = currentContentsProvider?.lastNumber!!.inc()
//                        loadContents(currentContentsProvider!!)
//                    }
//
//                    builder.setNegativeButton(
//                        "포기하자"
//                    ) { dialog, id ->
//                        dialog.dismiss()
//                    }
//                    builder.setNeutralButton(
//                        "같은 주소로 다시 도전"
//                    ) { dialog, id ->
//                        loadContents(currentContentsProvider!!)
//                        dialog.dismiss()
//                    }
//                    alertDialogs.add(builder.create())
//
//                    alertDialogs.last()?.show()
//
//                },500)
//            }
//
//        }
//
        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 {

                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) }
                } , {
                    it?.let { mainControllInterface.onFindTitle(it.replace("\"","")) }
                }, {btn ->
                    mainControllInterface?.showNextBtn (btn != null){
                        webview?.evaluateJavascript("if(document.getElementById('${currentContentsProvider!!.getNextButtonJs()}') != null) document.getElementById('${currentContentsProvider!!.getNextButtonJs()}').click()") {
                        }
                    }
                },{btn ->
                    mainControllInterface?.showPrevBtn(btn != null) {
                        webview?.evaluateJavascript("if(document.getElementById('${currentContentsProvider!!.getPrevButtonJs()}') != null) document.getElementById('${currentContentsProvider!!.getPrevButtonJs()}').click()") {
                        }
                    }
                }, { complete ->
                    if(complete) {
                        mainControllInterface?.completePageLoad(LastInfo().apply {
                            this.pageUrl = url ?: currentContentsProvider?.getLastedDoamin() ?: ""
                            this.contentsName = currentContentsProvider?.getWebcontentsName() ?: ""
                            this.pageIndex = 0
                        })
                    }
                })
            }
        }
    }
}