package com.adealink.weparty.webview

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import com.adealink.frame.log.Log
import com.adealink.weparty.App
import com.adealink.weparty.webview.constant.NATIVE_JS_BRIDGE
import com.adealink.weparty.webview.constant.TAG_WEB_VIEW
import com.adealink.weparty.webview.jsbridge.JSBridge
import com.adealink.weparty.webview.jsbridge.JSBridgeImpl

class WeNextWebView : BaseWebView {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
            super(context, attrs, defStyleAttr)

    override fun createDefaultJSBridge(): JSBridge {
        return JSBridgeImpl(this, NATIVE_JS_BRIDGE)
    }

    override fun loadUrl(urlP: String) {
        val url = requestUrl(urlP)
        if (url.isEmpty()) {
            Log.e(TAG_WEB_VIEW, "loadUrl, url is empty")
            return
        }

        val newUrl = App.instance.networkService.replaceUrlHost(url)
        Log.d(TAG_WEB_VIEW, "loadUrl, url:$urlP, newUrl:$newUrl")
        super.loadUrl(newUrl)
    }

    /**
     * 新旧版本兼容url处理
     */
    private fun requestUrl(url: String): String {
//        val oldVipUrlPrefix = "${UrlConfig.urlPrefix}/vip?"
//        if (url.startsWith(oldVipUrlPrefix)) {
//            return url.replace(oldVipUrlPrefix, "${UrlConfig.vip}?")
//        }

        return url
    }

    fun onDestroy() {
        try {
            loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            (parent as? ViewGroup)?.removeView(this)
            removeAllViewsInLayout()
            removeAllViews()
            webChromeClient = null
            destroy()
        } catch (e: Exception) {
            Log.e(TAG_WEB_VIEW, "release webview fail, for ${e.message}")
        }
    }

}