package com.adealink.weparty.webview.loader

import android.webkit.WebResourceResponse
import com.adealink.frame.log.Log
import com.adealink.weparty.webview.constant.TAG_WEB_VIEW_RES_LOAD

fun initWebResourceLoader(config: IWebResourceConfig) {
    WebResourceLoader.config = config
}

val webResourceLoader: IResourceLoader by lazy { WebResourceLoader() }

enum class LoaderType(val type: Int) {
    NORMAL(0),
    OKHTTP(1);

    companion object {
        fun map(type: Int): LoaderType {
            return values().firstOrNull { it.type == type } ?: NORMAL
        }
    }
}

internal class WebResourceLoader : IResourceLoader {

    companion object {
        internal var config: IWebResourceConfig = DefaultWebResourceConfig()
    }

    private val okHttpResourceLoader by lazy { OkHttpResourceLoader(config) }

    override fun load(request: ResourceRequest): WebResourceResponse? {

        return when (config.loaderType) {
            LoaderType.NORMAL -> {
                Log.d(
                    TAG_WEB_VIEW_RES_LOAD,
                    "normal load, url:${request.url}, method:${request.method}, redirect:${request.isRedirect}, forMainFrame:${request.isForMainFrame}, requestHeaders:${request.headers}"
                )
                null
            }
            LoaderType.OKHTTP -> okHttpResourceLoader.load(request)
        }
    }

}