package com.common.commonlib.net.interceptor

import android.text.TextUtils
import android.util.Log
import com.common.commonlib.BuildConfig
import com.common.commonlib.CommonApplication
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.BufferedInputStream
import java.util.*

/**
 * HOST拦截器:动态替换HOST
 *
 * @author wangym
 * @since 2021/7/28
 */
class BaseUrlInterceptor : Interceptor {
    /**
     * 拦截替换BaseUrl
     */
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest: Request = chain.request()
        val requestBuilder: Request.Builder = oldRequest.newBuilder()
        val headKey = BASE_URL_KEY
        val headValue: String? = oldRequest.header(headKey)
        // 判断是否需要替换BaseUrl,不需要则直接跳转
        if (TextUtils.isEmpty(headValue)) {
            return chain.proceed(chain.request())
        }
        // 该HEAD只用于替换BaseUrl,将对应的自定义HEAD去除
        requestBuilder.removeHeader(headKey)
        // 尝试获取新BaseUrl
        val newUrlValue = getValueFromProperties(headValue)
        val newBaseUrl: HttpUrl? = newUrlValue.toHttpUrlOrNull()
        // 获取到新BaseUrl进行替换
        return if (newBaseUrl != null) {
            val oldHttpUrl: HttpUrl = oldRequest.url
            val newUrl = oldHttpUrl.newBuilder()
                .scheme(newBaseUrl.scheme)
                .host(newBaseUrl.host)
                .port(newBaseUrl.port)
                .build()
            chain.proceed(requestBuilder.url(newUrl).build())
        } else {
            chain.proceed(chain.request())
        }
    }

    /**
     * 通过KEY从配置文件中获取值
     */
    private fun getValueFromProperties(key: String?): String {
        val prop = Properties()
        var value = ""
        try {
            val context = CommonApplication.getContext()
            if (context == null) {
                Log.e(TAG, "got context null, please init context!")
                return value
            }
            val mAssets = context.assets
            if (mAssets == null) {
                Log.e(TAG, "got assets null, please check the assets folder")
            }
            // 通过输入缓冲流进行读取配置文件
            val inputStream =
                BufferedInputStream(mAssets.open((BuildConfig.BASE_URL_CONFIG_PATH)))
            // 加载输入流
            prop.load(inputStream)
            // 根据关键字获取value值
            value = prop.getProperty(key);
        } catch (e: Exception) {
            Log.e(TAG, e.toString())
        }
        return value
    }

    companion object {
        const val TAG = "BaseUrlInterceptor"
        const val BASE_URL_KEY = "baseurl"
    }
}